我有一个div与位置相对在这个div是另一个绝对定位的div。现在我想收到PositionX和PositionY坐标。当我点击div中的“自由”点时,它工作得非常好,但是当我点击这个div中的绝对定位元素时,我得到错误的坐标。
https://jsfiddle.net/vqb56uf3/2/
$(".relative").click(function(e) {
$(".clickIndicator").css({
"left": e.offsetX + "px",
"top": e.offsetY + "px",
"display": "block"
});
});
.relative {
position: relative;
width: 500px;
height: 300px;
background: black;
}
.absolute {
position: absolute;
height: 30px;
width: 30px;
background: white;
}
.clickIndicator {
position: absolute;
border-radius: 100px;
width: 10px;
height: 10px;
background: red;
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="relative">
<div class="clickIndicator"></div>
<div class="absolute" style="top: 30px; left: 90px;"></div>
<div class="absolute" style="top: 200px; left: 340px;"></div>
<div class="absolute" style="top: 140px; left: 79px;"></div>
<div class="absolute" style="top: 230px; left: 211px;"></div>
<div class="absolute" style="top: 90px; left: 450px;"></div>
<div class="absolute" style="top: 80px; left: 260px;"></div>
</div>
答案 0 :(得分:2)
相对于文档左边缘的鼠标位置
此外,您可以通过增加.relative
位置来相对计算元素,如下所示:
$(".relative").click(function(e) {
var offset = $(this).offset();
$(".clickIndicator").css({
"left": e.pageX - offset.left + "px",
"top": e.pageY - offset.top + "px",
"display": "block"
});
});
.relative {
position: relative;
width: 500px;
height: 300px;
background: black;
}
.absolute {
position: absolute;
height: 30px;
width: 30px;
background: white;
}
.clickIndicator {
position: absolute;
border-radius: 100px;
width: 10px;
height: 10px;
background: red;
display: none;
z-index: 1;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="relative">
<div class="clickIndicator"></div>
<div class="absolute" style="top: 30px; left: 90px;"></div>
<div class="absolute" style="top: 200px; left: 340px;"></div>
<div class="absolute" style="top: 140px; left: 79px;"></div>
<div class="absolute" style="top: 230px; left: 211px;"></div>
<div class="absolute" style="top: 90px; left: 450px;"></div>
<div class="absolute" style="top: 80px; left: 260px;"></div>
</div>
答案 1 :(得分:0)
偏移量相对于事件目标。要获取点击事件的X,Y坐标,您需要考虑目标的位置。旧学校的JavaScript方法如下:
$('.filtr-item').on('click',function(){
$('#menuCarousel').find('.active').removeClass('active');
$('.'+$(this).attr('data-demo')+'_item').addClass('active');
});