jQuery 如何根据光标单击的位置定位弹出 div
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9220141/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to position a popup div based on the position of where the cursor clicks
提问by some_bloody_fool
I am trying to position a popup div below:
我正在尝试在下面放置一个弹出式 div:
<div style="display:none;height:200px;width:200px;border:3px solid green;" id="popup">Hi</div>
based on the clicking of another div.
基于另一个div的点击。
I am running this on document .ready
我在文档 .ready 上运行这个
$('div#d').bind('click', function (event) {
var offset = $(this).offset();
$('#popup').css('left',offset.left);
$('#popup').css('top',offset.top);
$('#popup').css('display','inline');
});
but the above will not even display the div
但上面甚至不会显示div
回答by Gigi
The problem lie in the fact that offset() do not return the correct mouse position, try event.pageX and event.pageY instead:
问题在于 offset() 没有返回正确的鼠标位置,请尝试使用 event.pageX 和 event.pageY:
$(document).ready(function(){
$('div#d').bind('click', function (event) {
$('#popup').css('left',event.pageX); // <<< use pageX and pageY
$('#popup').css('top',event.pageY);
$('#popup').css('display','inline');
$("#popup").css("position", "absolute"); // <<< also make it absolute!
});
});
See here.
见这里。
回答by mrtsherman
Try adding position: absolute
to your div. Make sure it isn't located within another div that has relative positioning.
尝试添加position: absolute
到您的 div。确保它不在另一个具有相对定位的 div 中。
<div style="position: absolute; display:none;height:200px;width:200px;border:3px solid green;" id="popup">Hi</div>
Top and left only work for elements with relative
, absolute
or fixed
positioning.
Top 和 left 仅适用于带有relative
,absolute
或fixed
定位的元素。