开发者

Easily position an element over another element in jQuery?

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?


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/


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.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜