使用 jQuery 显示相对于另一个元素的元素
我正在开发一个界面,要求用户可以单击按钮,然后我将显示一个相对于按钮定位的浮动 div(您可以将其视为单击向下箭头时显示的区域)下拉菜单)。
如何正确地将这个浮动元素放置在单击的按钮(可能位于页面上的任何位置)附近?
提前致谢!!
I am working on an interface that requires that the user can click on a button, and then I will show a floating div positioned relative to the button (you can kind of think of it as the area that shows when you click the down arrow on a dropdown).
How can I correctly position this floating element adjacent to the button which was clicked (which could be anywhere on the page)?
Thanks in advance!!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用
.offset()
获取按钮的位置例如:
这会将其放置在按钮的右侧,只需将左侧/顶部调整到您想要的位置即可。
例如,要将其放置在按钮下方,请将顶部部分更改为
'top':o.top + $(this).height()
或按钮的右侧:'left' :o.left + $(this).width()
You can get the position of the button by using
.offset()
For example:
This would position it right on top of the button, just adjust that left/top wherever in relation you want it to go.
For example to place it below the button change the top portion to
'top': o.top + $(this).height()
or to right right of the button:'left':o.left + $(this).width()
使用CSS:
和Javascript:
基本上你绝对定位浮动div以将其从正常流程中删除,然后使用
offset()
找出相对于按钮的放置位置。with CSS:
and Javascript:
Basically you absolutely position the floating div to remove it from the normal flow and then use
offset()
to figure out where to put it in relation to the button.您应该使用 .offset() 获取和设置位置,以防元素按层次定位。
例如2
这是一个小提琴: http://jsfiddle.net/R5YM6/1/
You should both get and set the position using .offset(), in case the element is positioned hierarchically.
For example2
Here is a fiddle: http://jsfiddle.net/R5YM6/1/