如何根据光标单击的位置放置弹出式div [英] How to position a popup div based on the position of where the cursor clicks
本文介绍了如何根据光标单击的位置放置弹出式div的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试在下面放置一个弹出div:
I am trying to position a popup div below:
<div style="display:none;height:200px;width:200px;border:3px solid green;" id="popup">Hi</div>
基于另一个div的点击.
based on the clicking of another div.
我正在.ready文件上运行此
I am running this on document .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');
});
但是上面的内容甚至不会显示div
but the above will not even display the div
推荐答案
问题在于,offset()不能返回正确的鼠标位置,请尝试使用event.pageX和event.pageY:
The problem lie in the fact that offset() do not return the correct mouse position, try event.pageX and event.pageY instead:
$(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!
});
});
请参见此处.
这篇关于如何根据光标单击的位置放置弹出式div的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文