简体   繁体   English

使用jQuery在div的10px中检测鼠标悬停

[英]Detect mouseover in 10px of div with jQuery

So I have like a div like this: 所以我像这样的div:

------------------ ------------------
------------------ ------------------
------------------ ------------------
------------------ ------------------

It is possible with javascript or jquery and without using any aditional tags to detect when the user overs this area which is 10px 可以使用javascript或jquery 而不使用任何附加标记来检测用户何时超过10px的区域

---------------- -- ---------------- -
---------------- -- ---------------- -
---------------- -- ---------------- -
---------------- -- ---------------- -

I know how to make it using aditional tags, but I would like to know if there is a better option, using only javascript. 我知道如何使用附加标记来实现,但是我想知道是否有更好的选择, 仅使用javascript。

You can attach event handler in JavaScript without any additional tags. 您可以在JavaScript中附加事件处理程序,而无需任何其他标签。 For example if you have a DIV like this: 例如,如果您有这样的DIV:

<div id="xdiv" style="width:100px; height:100px; border: solid 1px black" />

in pure JavaScript you can attach onmousemove like this: 在纯JavaScript中,您可以像这样附加onmousemove

document.getElementById("xdiv").onmousemove = function(e) {
    var evt = e || event;

    if (this.offsetWidth - evt.offsetX > 10) {
        this.style.backgroundColor = "red"
    } else {
        this.style.backgroundColor = "green"
    }
}

When you move the mouse over DIV it will become green if you move within 10px of the right side. 当您将鼠标移到DIV上时,如果您在右侧的10px范围内移动,它将变为绿色。 Otherwise it will be red. 否则它将为红色。

Live demo: http://jsfiddle.net/25SXW/3/ 现场演示: http : //jsfiddle.net/25SXW/3/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM