滚动页面时,如何准确地相对于鼠标指针定位div?

我在搜索中找到了这个例子 。

但它没用,因为当网页长度很高,而我的

块不在顶部时,当我滚动页面时,不同的PageYclientY有不同的距离,所以可移动的

不能完全按照鼠标光标。

这是我到目前为止所尝试的内容:

 jQuery("#requestStatusChart").mouseover(function (event) { var maskVal = '' + +'
'; 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上的鼠标位置,但是这段代码表明它远非理想。

 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; } 
 
Hi
content just to make the container taller

我用另一种方法解决了这个问题。 在X轴我们可以这样做。

内容表示您的主程序宽度,代码适应所有分辨率。

 var widthContent = jQuery("#content").width(); jQuery("#floatTip").css("left", _xx - (window.screen.width - widthContent)/2 + "px");