我正在处理一个映射功能,并且将元素与鼠标位置对齐的jQuery脚本具有似乎与页面间距匹配的偏移量。使用jQuery将元素与鼠标位置对齐有一个偏移
这里是试验区http://champagnecentre.com/dev/directory/
jQuery(document).mousemove(function(e){
jQuery('.directory-listing').css({top:e.pageY,left:e.pageX});
});
我正在处理一个映射功能,并且将元素与鼠标位置对齐的jQuery脚本具有似乎与页面间距匹配的偏移量。使用jQuery将元素与鼠标位置对齐有一个偏移
这里是试验区http://champagnecentre.com/dev/directory/
jQuery(document).mousemove(function(e){
jQuery('.directory-listing').css({top:e.pageY,left:e.pageX});
});
编辑:按@下面Bwolfing的评论,我对规范的解释是不正确的。我已经更新了下面的plunk,为上面提出的替代解决方案提出了建议。将工具提示的位置更改为fixed
将强制它相对于页面。
https://plnkr.co/8CCns5mwdqSoWiGK1SDN
HTML
<!DOCTYPE html>
<html>
<head>
<script data-require="[email protected]" 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;
}
'$ .css({top:e.pageY,left:e.pageX})'只是一小部分。如果您将[object]传递给'$ .css'](http://api.jquery.com/css/#css-properties),则会将这些键视为样式属性,将值视为样式值。换句话说,你建议的解决方法就是迈克尔已经在做的事情。更可能的是,问题是被移动的div是相对于错误的元素 – Bwolfing
@Bwolfing你是对的。我不知道如何,但我完全错过了规范,这是我见过的第一次在实践中使用。我很抱歉。 –
@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>
欢迎到StackOverflow!请提供您的尝试的[最小,完整和可验证示例](http://stackoverflow.com/help/mcve)。作为[Stack Snippet](https://blog.stackoverflow.com/2014/09/introducing-runnable-javascript-css-and-html-code-snippets/) – andreas
我注意到的一件事是'.directory-listing据我所知,'divs并不嵌套在'postition:relative'元素下。当我添加“position:relative;”到父元素之一时,它帮助定位。它并没有使它正确,但它使它更接近 – Bwolfing
这是演示:https://smalinux.github.io/svgTemp.html,你可以从这里下载代码:https://github.com/smalinux/smalinux .github.io/blob/master/svgTemp.html –