如何检测.targ元素的右半部分或左半部分是否发生了点击?
$(document).on('click', '.targ', function(e) {
let targ = $(this);
let center = targ.width() / 2;
let x = '???'; // here I need clicked PositionX relative to targ
if (x > center) {
console.log('clicked right');
} else {
console.log('clicked left');
}
});Run Code Online (Sandbox Code Playgroud)
.parent {
text-align: center;
}
.targ {
display: inline-block;
text-align: center;
background: orange;
}Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='parent'>
<div class='targ'>LOREM IPSUM</div>
</div>Run Code Online (Sandbox Code Playgroud)
您可以从提供给事件处理程序的事件的offsetX和offsetY属性中获取元素内单击位置的 X 和 Y 坐标。然后您可以将其与计算的中心点进行比较。尝试这个:
$(document).on('click', '.targ', function(e) {
let center = $(this).width() / 2;
if (e.offsetX > center) {
console.log('clicked right');
} else {
console.log('clicked left');
}
});Run Code Online (Sandbox Code Playgroud)
.parent {
text-align: center;
}
.targ {
display: inline-block;
text-align: center;
background: orange;
}Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="parent">
<div class="targ">LOREM IPSUM</div>
</div>Run Code Online (Sandbox Code Playgroud)