我正在开发一个映射特性,将元素与鼠标位置对齐的jQuery脚本的偏移量似乎与页面间距相匹配。
这是测试区域http://champagnecentre.com/dev/directory/
jQuery(document).mousemove(function(e){
jQuery('.directory-listing').css({top:e.pageY,left:e.pageX});
});发布于 2016-09-23 07:35:40
@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>
发布于 2016-09-23 05:38:08
编辑:根据@Bwolfing下面的评论,我对规范的解释是不正确的。我已经更新了下面的plunk,为上面提出的建议提出了一个替代解决方案。将工具提示的位置更改为fixed会强制它相对于页面。
https://plnkr.co/8CCns5mwdqSoWiGK1SDN
HTML
<!DOCTYPE html>
<html>
<head>
<script data-require="jquery@2.2.4" data-semver="2.2.4" src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body>
<div class="offsetWrapper">
<h1 id="myH1">Hello Plunker!</h1>
</div>
</body>
</html>JS
$(document).on ('mousemove', function (event)
{
$('#myH1').css ({'left', event.pageX, 'top', event.pageY});
});CSS
#myH1 {
position: fixed;
margin: 0;
}
.offsetWrapper {
position: relative;
left: 100px;
top: 100px;
/*Show the position of the container for reference*/
background-color: red;
height: 10px;
width: 10px;
}https://stackoverflow.com/questions/39649039
复制相似问题