确定鼠标点击是否发生在DIV的左半部分或右半部分 [英] Determining if mouse click happened in left or right half of DIV

查看:112
本文介绍了确定鼠标点击是否发生在DIV的左半部分或右半部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 我想知道是否可以计算鼠标点击发生在div元素的左侧还是右侧> $(div)。click(function(e){
//计算点击发生在左半部还是右半部
});


< div>可变内容< / div>

希望有一种方法可以获得相对坐标并将它们与div的宽度相关联

解决方案

  $(div)。click(function(e){
var pWidth = $(this).innerWidth(); //使用.outerWidth()如果你想要边框
var pOffset = $(this).offset();
var x = e .pageX - pOffset.left;
if(pWidth / 2> x)
$(this).text('left');
else
$(this)。文字('right');
});

DEMO:
http://jsfiddle.net/dirtyd77/QRKn7/1/



希望这有助于!如果您有任何问题,请告知我!


I was wondering if it's possible to calculate if a mouse click happened over the left or right half of the div element:

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


<div>Variable Content</div>

Was hoping there would be a way to get the relative coordinates and relate them to the width of the 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');
});

DEMO: http://jsfiddle.net/dirtyd77/QRKn7/1/

Hope this helps! Let me know if you have any questions!

这篇关于确定鼠标点击是否发生在DIV的左半部分或右半部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆