我試圖讓滑鼠在正方形內偏移,但是當我單擊它的子級時,偏移量會發生變化,現在回傳子級內的滑鼠偏移量,而不是父級。
我想要實作的是讓滑鼠在父級內部偏移,即使我在子級內部單擊也是如此。非常感謝!
下面是一個問題的例子。(查看控制臺)
$("#parent").click(function(e){
console.log(e.offsetX, e.offsetY)
});
.square{
position: relative;
height: 200px;
width: 200px;
background-color: red;
}
.small{
position: absolute;
top: 25px;
right: 25px;
height: 50px;
width: 50px;
background-color: blue;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="square" id="parent">
<div class="square small"></div>
</div>
uj5u.com熱心網友回復:
添加pointer-events: none;
到“小”類的 css 中會禁用單擊元素。
$("#parent").click(function(e){
console.log(e.offsetX, e.offsetY)
});
.square{
position: relative;
height: 200px;
width: 200px;
background-color: red;
}
.small{
position: absolute;
top: 25px;
right: 25px;
height: 50px;
width: 50px;
background-color: blue;
pointer-events: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="square" id="parent">
<div class="square small"></div>
</div>
uj5u.com熱心網友回復:
您可以使用
e.target
讓元素被點擊,就像this
點擊冒泡的父元素一樣。
然后結合 with.getBoundingClientRect()
得到它的位置,給出:
$("#parent").click(function(e) {
var rect = e.target.getBoundingClientRect();
//console.log(e.offsetX, e.offsetY)
//console.log(rect.left, rect.top)
console.log(rect.left e.offsetX, rect.top e.offsetY)
});
.square {
position: relative;
height: 200px;
width: 200px;
background-color: red;
}
.small {
position: absolute;
top: 25px;
right: 25px;
height: 50px;
width: 50px;
background-color: blue;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="square" id="parent">
<div class="square small"></div>
</div>
uj5u.com熱心網友回復:
解決方案
將透明背景以及全高和全寬子 div 添加到父級 ( #parent-overlay
) 并檢查其偏移量。
為什么
偏移量是從點擊事件中獲得的,并且點擊事件發生在孩子身上。因此,在子級中,您無法從父級獲得偏移量(事件已在子級上注冊)。
添加與父級匹配的完整寬度和高度疊加層,并從那里獲得偏移量應該可以滿足您的需求。
$("#parent-overlay").click(function(e) {
console.log(e.offsetX, e.offsetY);
});
.square{
position: relative;
height: 200px;
width: 200px;
background-color: red;
}
.small{
position: absolute;
top: 25px;
right: 25px;
height: 50px;
width: 50px;
background-color: blue;
z-index: 1;
}
#parent-overlay {
position: absolute;
z-index: 3;
top: 0;
left: 0;
bottom: 0;
right: 0;
background-color: transparent;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="square" id="parent">
<div id="parent-overlay"></div>
<div class="square small"></div>
</div>
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/437569.html
標籤:javascript jQuery 事件 点击 抵消
上一篇:以正確的方式隱藏元素
下一篇:計算匹配的字母一次