简体   繁体   English

将div相对于鼠标位置定位

[英]Positioning the div relative to mouse position

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.. 如何相对于鼠标位置定位以下div,以便鼠标和div不会在页面的末端不同步。可能就像一个工具提示总是在页面的末尾显示完美的位置。

<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........ 谢谢........

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});  
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM