当我使用jquery单击一个div时,如何获取相对于父div的offsetX

发布于 2024-10-04 22:32:49 字数 603 浏览 0 评论 0原文

这是我的代码:

<div id="a" style="position:absolute;width:200px;height:200px;background:red;word-wrap:break-word;">
            <div id="b" style="width:50px;height:50px;background:blue;"></div>
</div>

脚本是:

$( "#b" ).draggable({ containment: 'parent' });
$('#a').click(function(e){
        alert(e.pageX)
        //return false;
    })

e.pageX 相对于 window

如何获取相对于父 div 的 x,y ?

演示在这里:http://jsfiddle.net/KwYjr/2/

谢谢

this is my code:

<div id="a" style="position:absolute;width:200px;height:200px;background:red;word-wrap:break-word;">
            <div id="b" style="width:50px;height:50px;background:blue;"></div>
</div>

the script is :

$( "#b" ).draggable({ containment: 'parent' });
$('#a').click(function(e){
        alert(e.pageX)
        //return false;
    })

the e.pageX is Relative to the window ,

how to get the x,y Relative to the parent div ?

the demo is here :http://jsfiddle.net/KwYjr/2/

thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

素食主义者 2024-10-11 22:32:49

有关 jQuery 中事件对象的信息,请参阅以下文档: http://api.jquery .com/category/events/event-object/

您将看到它规范化了某些属性(在浏览器上保持相同),但不是全部。您需要的是 .offsetX

http://jsfiddle.net/KwYjr/3/

请注意 .offsetX 并不总是在某些浏览器中定义。通常有一个可以使用的事件中的替代变量。否则,获取您想要从中获取值的元素的 .offset() 位置,然后对其使用 .pageX

尝试使用e.pageX - e.target.offsetLefthttp://jsfiddle.net /KwYjr/7/

See the following documentation for information on the Event object in jQuery: http://api.jquery.com/category/events/event-object/

You will see that it normalises (makes the same over browsers) some of the properties, but not all. The one you need is .offsetX.

http://jsfiddle.net/KwYjr/3/

Note that .offsetX is not always defined in some browsers. There is usually an alternate variable in the event that can be used. Otherwise get the .offset() position of the element you want the value from and then use .pageX with it.

Try using e.pageX - e.target.offsetLeft: http://jsfiddle.net/KwYjr/7/

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文