确定鼠标是否发生在DIV的左半部分或右半部分

我想知道是否可以计算鼠标单元的左半部分还是右半部分是否发生了鼠标点击:

$("div").click(function(e){ // calculate if click happened on left or right half }); 
Variable Content

希望有办法获得相对坐标并将它们与div的宽度联系起来?

 $("div").click(function(e){ var pWidth = $(this).innerWidth(); //use .outerWidth() if you want borders var pOffset = $(this).offset(); var x = e.pageX - pOffset.left; if(pWidth/2 > x) $(this).text('left'); else $(this).text('right'); }); 

演示: http : //jsfiddle.net/dirtyd77/QRKn7/1/

希望这可以帮助! 如果您有任何疑问,请告诉我!

这应该这样做:

 $("div").click(function(e){ var $div = $(this); alert(e.pageX >= ($div.offset().left + $div.width()/2) ? 'clicked right' : 'clicked left'); }); 
 var x = evt.pageX - $(this).offset().left if (x > $(this).width()/2) { //Right half } else { //Left half } 

所以完整的代码将是

 $("div").click(function(e){ // calculate if click happened on left or right half var x = evt.pageX - $(this).offset().left if (x > $(this).width()/2) { //Right half } else { //Left half } }); 

要获得鼠标位置,您可以计算鼠标位置和div偏移之间的差异。 然后将它与div本身的半宽和voilà进行比较。

编辑

 $(function () { $("#test").click(function(e){ var offset = $(this).offset(); var pos_x = e.pageX - offset.left; var middle = $(this).outerWidth() / 2; if(pos_x < middle) { alert('left part'); } else { alert('right part'); } }); }); 

你可以在这里查看:

http://jsfiddle.net/kZuML/

小提琴,因为你知道 – YOLO!

 $("#special").on('click', function(e){ var x = e.pageX - this.offsetLeft; var y = e.pageY - this.offsetTop; //You probably don't need Y. Unless you want to know height as well. var width = $(this).width(), where = width / 2; if( x > where ){ console.log("Click was on the right"); } else { console.log("Click was on the left"); } }); 

PURE JAVASCRIPT解决方案 – 加入聚会后期。 但是使用我的代码重新做到这一点。 在body标签或div上给它ID并调用javascript函数,例如。 id =“tt”onclick =“showCoords(event)”

  function showCoords(event) { var x = event.clientX; var y = event.clientY; // var coor = "X coords: " + x + ", Y coords: " + y; // document.getElementById("demo").innerHTML = coor; var ele = document.getElementById("tt"); var width = ele.offsetWidth; var height = ele.offsetHeight; var half=(width/2); if(x>half) { alert('right click'); } else { alert('left click'); } }