简体   繁体   English

如何动态地将一个元素置于另一个元素之上?

[英]How do you dynamically position one element on top of another?

I'm dynamically appending some html with jQuery and I want to insert it directly on top of another element. 我用jQuery动态地附加一些html,我想直接在另一个元素的顶部插入它。 How do I do this? 我该怎么做呢?

this is the code in my application.js file: 这是我的application.js文件中的代码:

$(document).ready(function() {
$('a.oembed').embedly({maxWidth:300,'method':'replace'}).bind('embedly-oembed', function(e, oembed){
      $("#video_div").append($("<img>", { src: oembed.thumbnail_url, width:200 }));
   });
});

The image is being inserted dynamically, and I want it to be directly on top of this: 图像是动态插入的,我希望它直接在这上面:

<div id="video_div"><%= link_to 'video', @video.video_url, :class => 'oembed' %></div>

This is more like a CSS question. 这更像是一个CSS问题。 You want to make sure the parent element (#video_div) is positioned relatively (position: relative) and the inserted element (the img) is positioned absolutely (position: absolute) 你想确保父元素(#video_div)位于相对位置(位置:相对),插入元素(img)绝对定位(位置:绝对)

Hook it to the top left, make sure they're the same size and you're golden. 将它钩在左上方,确保它们的大小相同,你就是金色的。

#video_div {
  position: relative;
  width: 300px;
  height: 300px;
}

#video_div img {
  position: absolute;
  top: 0px;
  left: 0px;
  width: 300px;
  height: 300px;
}

Assuming you mean directly on top of it (obscuring it) in the z-order, a combination of JQuery's .position() method and absolute positioning should do the trick. 假设你在z顺序中直接表示它(隐藏它),JQuery的.position()方法和绝对定位的组合应该可以解决问题。

$('<div>New Element</div>').css({
    "position" : "absolute",
    "left"     : $foo.position().left,
    "top"      : $foo.position().top
}).appendTo($container);

Note: $container must contain both the dynamically generated element and the target element. 注意: $container必须包含动态生成的元素和目标元素。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM