2

Javascript中检测鼠标事件是否发生在元素的客户区域内部或外部的正确方法是什么?

我有一个带有边框和滚动条的容器,用作控制组。当用户单击容器客户区域内的任何位置时,我想以编程方式聚焦组中的活动元素,而不是当他们单击 scollbar 时。

4

3 回答 3

6

Actually instead of using clientWidth etc you can just use other properties of the rect. This makes the code simple and is more universal (should work for SVG elements too):

/**
 * Check whether the event occurred roughly inside (or above) the element.
 * 
 * @param {MouseEvent} event Event to check.
 * @param {Node} element Element to check.
 */
function isEventInElement(event, element)   {
    var rect = element.getBoundingClientRect();
    var x = event.clientX;
    if (x < rect.left || x >= rect.right) return false;
    var y = event.clientY;
    if (y < rect.top || y >= rect.bottom) return false;
    return true;
}

Note that getBoundingClientRect works even for transformed element and also works with scroll (and with zoom if your are on mobile). And browser support is very good for the basic properties (see MDN).

You could also add some margin to support bigger tap areas.

于 2019-01-02T02:31:27.413 回答
0

这是工作示例 http://jsfiddle.net/kYC9u/ ,下面是代码片段。希望这可以帮助

    <button onclick="doSomething('param');" id="id_button">action</button>
    <button onclick="doSomething('param');" id="id_button1">action2</button>




function doSomething(param,e)
        {
         if (!e)  e = window.event;
        var source1 = e.target || e.srcElement;
            console.log(source1.id);
        alert(source1.id);
        if(window.event) // IE8 and earlier
            {
            //doSomething
            }
        else if(e.which) // IE9/Firefox/Chrome/Opera/Safari
            {
            //doSomething
            }

        }
于 2013-05-06T17:44:39.367 回答
0

我想出了如何做到这一点。下面的代码可能只适用于支持getBoundingClientRect.

function isMouseEventInClientArea(event)
{
    var element = event.currentTarget;
    var rect = element.getBoundingClientRect();
    var minX = rect.left + element.clientLeft;
    var x = event.clientX;
    if (x < minX || x >= minX + element.clientWidth) return false;
    var minY = rect.top + element.clientTop;
    var y = event.clientY;
    if (y < minY || y >= minY + element.clientHeight) return false;
    return true;
}
于 2013-05-08T14:35:03.367 回答