开发者

How can I ignore all children elements with JQuery

I've this code:

$('.div2').mousemove(function(e) {
    var posX = (50 - (e.offsetX) / $(this).width() * 100);
    var posY = (-50 + (e.offsetY) / $(this).height() * 100);
    $('.results').html(posX+', '+posY);
});

And this html:

<div class="div1">
  <div class="div2">
    <ul>
      <li>Item 1</li>
      <li>Item 2</li>
      <li>Item 3</li>
    </ul>
  </div>
</div>
<div class="results"></div>

it works only when mouser don't hover items... how can I ignore them, but getting right value?

I've tried:

if(e.target != th开发者_如何学Cis){
    return true;
}

but don't get right value over items...


Welcome to Stack Overflow!

Use the event attributes layerX and layerY to get the desired values. The offsetX and offsetY attributes are always relative to the element that is below the cursor, even though the event is bound to a parent. The same applies to the target attribute.

Also, I prefer using currentTarget since it makes your code a bit easier to read and understand without having to trace the origin of this.

$('.div2').mousemove(function(e) {
    var posX = (50 - (e.layerX) / $(e.currentTarget).width() * 100);
    var posY = (-50 + (e.layerY) / $(e.currentTarget).height() * 100);
    $('.results').html(posX+', '+posY);
});

Check out my test case on jsFiddle

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜