This question already has answers here:
Determining if mouse click happened in left or right half of DIV

(7个答案)


在11个月前关闭。




如何检测.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');
  }
});
.parent {
  text-align: center;
}

.targ {
  display: inline-block;
  text-align: center;
  background: orange;
}
<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>

最佳答案

您可以从提供给事件处理程序的事件上的offsetXoffsetY属性获取元素内单击位置的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');
  }
});
.parent {
  text-align: center;
}

.targ {
  display: inline-block;
  text-align: center;
  background: orange;
}
<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>

10-08 12:39