javascript 将图像定位在没有包装器的 div 底部

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7284497/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 23:34:57  来源:igfitidea点击:

position image at bottom of div without wrapper

javascriptimagehtmlposition

提问by Lukasz

How would I position an image at the bottom of a div using JavaScript without wrapping it? I understand I can wrap it with a div and do absolute positioning, but that muddies up the markup and it's dynamic content too, so I can't wrap the image, it has to target an image in a specific div.

如何使用 JavaScript 将图像定位在 div 的底部而不包装它?我知道我可以用 div 包装它并进行绝对定位,但这会使标记变得混乱,而且它也是动态内容,所以我无法包装图像,它必须将图像定位在特定的 div 中。

Here is the basic markup, need it to find height of div, then position image at bottom. i think that is how it would work?

这是基本标记,需要它来找到 div 的高度,然后将图像定位在底部。我认为这就是它的工作方式?

<div id="content">
 <p>some text</p>
 <img src="img.jpg"/>
</div>

回答by margusholland

You can position an image as well to the bottom of a DIV, you don't need to add a second wrapper. Either do it in CSS:

您也可以将图像定位到 DIV 的底部,无需添加第二个包装器。要么在 CSS 中做:

div { position: relative; } 

div > img { position: absolute; bottom: 0; }

or do the same thing in JS if you need it be in JS.

或者如果你需要在 JS 中做同样的事情。

回答by margusholland

As simple as this~~

就这么简单~~

#content
{ position:relative; padding-bottom:50px; } // if image height is 50px;
#content > img
{ position:absolute; bottom:0; }

That should do it. If you don't use padding-bottomin the second rule, the image will be overflowed (and will cover the text) if the content of the div (its text) is not taller that the image height.

那应该这样做。如果在第二条规则中不使用padding-bottom,如果 div 的内容(其文本)不高于图像高度,图像将溢出(并覆盖文本)。

回答by Loktar

I would do it using CSS for sure, and don't recommend doing it this way.. but you can do it with JS like so

我肯定会使用 CSS 来做到这一点,并且不建议这样做。但是您可以像这样使用 JS 来做到这一点

Live Demo

现场演示

var image = document.getElementById("image"),
    contentDiv = document.getElementById("content");

image.style.position = 'absolute';
image.style.top = contentDiv.offsetTop + contentDiv.offsetHeight - image.offsetHeight + 'px';