在 jQuery 中轻松地将一个元素定位在另一个元素上?

发布于 2024-08-29 06:56:15 字数 137 浏览 2 评论 0原文

我需要使用 jQuery 将 div 放置在图像上。我可以使用 position:fixed 创建它,并使用顶部和左侧使用元素偏移来定位它,但它很糟糕,因为如果用户滚动,该元素将不会位于该元素的顶部。

还有其他想法吗?

I need to position a div over an image with jQuery. I can create it with using position: fixed and use top and left to position it using elements offset, but it sucks because the element will not be on top of the element if user scrolls.

Any other ideas?

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

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

发布评论

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

评论(2

Saygoodbye 2024-09-05 06:56:15

如果您在多个位置执行此操作,则可以执行以下操作:

<div style="position: relative;">
  <div style="position:absolute; width: 276px; height: 110px; z-index: 2;">
    Content here will be on top the image
  </div>
  <img style="width: 276px; height: 110px;" src='http://www.google.com/intl/en_ALL/images/logo.gif' alt="Test Img" />
</div>​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​

如果您匹配内部/外部 div 上的 height/width 样式属性,则内部 < ;div> 位于 之前,并且您为内部

提供了更高的 z-索引比图像高,它将与图像完美重叠。

您可以在此处查看实际操作的示例:http://jsfiddle.net/ZcBus/

If you're doing this multiple places, you can do this:

<div style="position: relative;">
  <div style="position:absolute; width: 276px; height: 110px; z-index: 2;">
    Content here will be on top the image
  </div>
  <img style="width: 276px; height: 110px;" src='http://www.google.com/intl/en_ALL/images/logo.gif' alt="Test Img" />
</div>​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​

If you match the height/width style attributes on the inner/ouer divs, the inner <div> comes before the <img /> and you give the inner <div> a higher z-index than the image, it'll perfectly overlap the image.

You can see an example of this in action here: http://jsfiddle.net/ZcBus/

月野兔 2024-09-05 06:56:15

创建一个带有position:relative的容器div。然后将图像放置在 div 内,并将原始 div 放置为位置:绝对,但坐标相对于容器 div。例如,

<div style='position:relative'>
  <img src='' alt=''/>
  <div id='original' style='position:absolute; top:10px; left:50px'/>
</div>

您可以使用 jQuery 注入部分或全部标记,或者更改样式,但根本不必使用脚本。

Create a container div with position:relative. Then place your image inside the div, and also your original div as position:absolute, but in coordinates relative to the container div. eg

<div style='position:relative'>
  <img src='' alt=''/>
  <div id='original' style='position:absolute; top:10px; left:50px'/>
</div>

You can use jQuery to inject some or all of that markup, or change the style but you dont have to use script at all.

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