如何使用 JQuery 忽略所有子元素
我有这段代码:
$('.div2').mousemove(function(e) {
var posX = (50 - (e.offsetX) / $(this).width() * 100);
var posY = (-50 + (e.offsetY) / $(this).height() * 100);
$('.results').html(posX+', '+posY);
});
和这个 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>
它仅在鼠标不悬停项目时才有效...我如何忽略它们,但获得正确的值?
我已经尝试过:
if(e.target != this){
return true;
}
但没有获得正确的物品价值......
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 != this){
return true;
}
but don't get right value over items...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
欢迎来到堆栈溢出!
使用事件属性
layerX
和layerY
来获取所需的值。offsetX
和offsetY
属性始终相对于光标下方的元素,即使事件绑定到父级也是如此。这同样适用于target
属性。另外,我更喜欢使用 currentTarget,因为它使您的代码更容易阅读和理解,而无需追踪
this
的起源。查看我的 jsFiddle 测试用例
Welcome to Stack Overflow!
Use the event attributes
layerX
andlayerY
to get the desired values. TheoffsetX
andoffsetY
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 thetarget
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
.Check out my test case on jsFiddle