最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Positioning the div relative to mouse position - Stack Overflow

programmeradmin5浏览0评论

All,

How to Position the following div relative to mouse position so that the mouse and div are not out ofsync at theend of the page.May be just like a tooltip which always sjows the perfect position at the end of the page..

<style type="text/css">
#div1 { width: 200px; height: 30px; background-color: #a9a9a9; color: #fff; position: absolute; }
 </style>
<script src="jquery.js" type="text/javascript"></script>
<script type="text/javascript">
$(function(){
$(window).mouseover(function(event){
$("#div1").css({'top': event.pageY, 'left': event.pageX});  
});
});
</script>
<div id="div1">mouseover me</div>

Thanks........

All,

How to Position the following div relative to mouse position so that the mouse and div are not out ofsync at theend of the page.May be just like a tooltip which always sjows the perfect position at the end of the page..

<style type="text/css">
#div1 { width: 200px; height: 30px; background-color: #a9a9a9; color: #fff; position: absolute; }
 </style>
<script src="jquery.js" type="text/javascript"></script>
<script type="text/javascript">
$(function(){
$(window).mouseover(function(event){
$("#div1").css({'top': event.pageY, 'left': event.pageX});  
});
});
</script>
<div id="div1">mouseover me</div>

Thanks........

Share Improve this question asked Feb 8, 2010 at 3:56 HulkHulk 34.2k64 gold badges150 silver badges217 bronze badges 0
Add a ment  | 

1 Answer 1

Reset to default 6

You can try with this example,

$(window).mouseover(function(event){
    var x = event.pageX,
        y = event.pageY,
        scX = $(window).scrollLeft(),
        scY = $(window).scrollTop(),
        scMaxX = scX + $(window).width(),
        scMaxY = scY + $(window).height(),
        wd = $("#div1").width(),
        hgh = $("#div1").height();

    if (x + wd > scMaxX) x = scMaxX - wd;
    if (x < scX) x = scX;
    if (y + hgh > scMaxY) y = scMaxY - hgh;
    if (y < scY) y = scY;
    $("#div1").css({'top': y, 'left': x});  
});
发布评论

评论列表(0)

  1. 暂无评论