滚动页面时,如何准确地相对于鼠标指针定位div? [英] How do I position a div relative to the mouse pointer exactly when scroll page?
问题描述
我在搜索中找到了此示例。
但它没用,因为当网页长度较长时,我的< div>
块isn'在顶部,当我滚动页面时,不同的距离有不同的 PageY
或 clientY
,所以可移动< div>
无法完全跟踪鼠标光标。
But it is useless, because when the webpage has long height, and my <div>
block isn't on the top, when I scroll the page, there are different distances with different PageY
or clientY
, so the movable <div>
can not exactly go after the mouse cursor.
这是我到目前为止所尝试的内容:
Here's what I've tried so far:
jQuery("#requestStatusChart").mouseover(function (event) {
var maskVal = '<span id="floatTip" style="position:absolute"><span id="hintdivlogistics" class="RMAHintdivlogistics">' +
+'</span><div class="clear"></div></span>';
jQuery(this).find(".DashboardMask").append(maskVal)
ShowHintInfoLogistics("abc");
//when onmouse out ,remove the elements I appended before.
jQuery(this).find(".DashboardMask").mouseout(function () {
if (typeof jQuery("#hintdivlogistics") != undefined) {
jQuery("#floatTip").fadeOut("slow").remove();
}
});
//move current row
jQuery(this).find(".DashboardMask").mousemove(function (event) {
_xx = event.clientX;
_yy = event.clientY;
_yyPage = event.pageY;
var pos = jQuery(this).position();
console.log((pos.left + " " + pos.top));
jQuery("#floatTip").css({ "top": _yy + "px", "left": _xx - 180 + "px",
"border": "2px solid red"
}).fadeIn("slow");
console.log("x:" + _xx + ",y:" + _yy / _yyPage * _yy);
return false;
});
return false;
});
推荐答案
我不知道有什么方法可以做到这一点鉴于您在没有鼠标事件的情况下不知道鼠标的位置,因此可靠。您可以跟踪mousemove上的鼠标位置,但是这个片段显示它远非理想。
I don't know of any way to do that reliably, given that you don't know the position of the mouse without a mouse event. You could keep track of the mouse position on mousemove, but as this snippet demonstrates it's far from ideal.
function mousemoved(event) {
var f = document.querySelector('#floater');
console.log(event);
f.style.top = event.pageY + f.scrollTop + 'px';
f.style.left = event.pageX + 'px';
}
document.querySelector('#container').addEventListener('mousemove', mousemoved);
#container {
overflow: scroll;
position: relative;
}
#content {
height: 4000px;
background: lightblue;
}
#floater {
position: absolute;
border: 1px solid black;
padding: 1em 2em;
}
<div id="container">
<div id="floater">Hi</div>
<div id="content">content just to make the container taller</div>
</div>
这篇关于滚动页面时,如何准确地相对于鼠标指针定位div?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!