我正在尝试使用 Bootstrap 获取模态窗口设置内的 x 和 y 坐标。单击图像时会弹出模态窗口,但是当我单击模态窗口上的任意位置时,它会为我提供相对于浏览器窗口而不是模态窗口的坐标。
HTML:
<div style="width: 200px; height: 200px;background-color: red; margin: 200px
auto">
<img src="image/Chrysanthemum.jpg" width="100%" height="100%" alt="">
</div>
<div id="myModal" class="modal fade" role="dialog">
<div class="modal-dialog" >
<!-- Modal content-->
<div class="modal-content" style="width: 700px; height: 600px">
<div class="modal-body">
<img src="" alt="" id="modal-img" width="100%" height="100%">
</div>
</div>
JQuery:
$("img").on("click",(function(){
var imgsrc = $(this).attr("src");
$("#modal-img").attr("src",imgsrc);
$("#myModal").modal("show");
}));
$("#myModal").on("click",function(e){
var relativeX = e.pageX - this.offsetLeft;
var relativeY = e.pageY - this.offsetTop;
alert(relativeX + " " + relativeY);
});
最佳答案
您的 #myModal 元素是模态框的全宽背景,因此 offsetTop 和 offsetLeft 始终为 0;您想要的是将对话定位在背景中。
$("#myModal").on("click",function(e){
var dialogElm = $("#myModal .modal-dialog");
var relativeX = e.pageX - dialogElm.offset().left;
var relativeY = e.pageY - dialogElm.offset().top;
alert(relativeX + " " + relativeY);
});
关于jquery - Bootstrap 模态窗口上的鼠标 x y 位置不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46626376/