使用jQuery将元素对齐到鼠标位置有一个偏移量
Using jQuery to align an element to mouse location has an offset
我正在开发一个映射功能,jQuery脚本将元素对齐到鼠标位置,其偏移量似乎与页面间距相匹配。
这里是测试区http://champagnecentre.com/dev/directory/
jQuery(document).mousemove(function(e){
jQuery('.directory-listing').css({top:e.pageY,left:e.pageX});
});
@Bwolfing是对的。e.pageY
和e.pageX
与文档相关。当你的div嵌套时,top
和left
的位置是相对于父元素的,这导致了偏移。
通过使用.parent().offset()
,我们可以锻炼偏移量,如下所示。我将.area
添加为移位的div,其中嵌套.directory-listing
, .mousemove
函数可归因于$(document)...
或$('.area')...
,请注意,.mousemove
最好编写为.on
的主题:
$(document).on({
mouseenter: function(e) {
// special effects
},
mousemove: function(e) {
e.preventDefault();
var target = $('.directory-listing'),
d = target.parent().offset(), // this gets the offset positions
dX = d.left + 6,
dY = d.top + 12; // the +6 and +12 here are just to center the 'x'
target.css({
left: e.pageX - dX,
top: e.pageY - dY
});
},
mouseleave: function(e) {
// special effects
},
click: function(e) {
// special effects
}
});
.area {
position: absolute;
left: 10%;
top: 100px;
width: 40%;
height: 50%;
background: #bbb;
border: 1px solid #09f;
}
.directory-listing {
position: absolute;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<div class="area">
<div class="directory-listing">X</div>
</div>
编辑:根据@Bwolfing下面的评论,我对规范的解释是不正确的。我已经更新了下面的问题,提出了上面建议的替代解决方案。将工具提示的位置更改为fixed
将强制其相对于页面。