gpt4 book ai didi

javascript - 在 Javascript 中设置 img 的边距

转载 作者:太空宇宙 更新时间:2023-11-03 20:19:42 24 4
gpt4 key购买 nike

下面的代码调整了 img 的边距,因此它在宽度为 600px 的 div 中居中。它通常有效,但有时无效,需要进行第二次调用。

编辑:忘了说:这个函数是被另一个人触发的,他将图像的来源设置为另一个人,因此改变了图像。

有什么帮助吗?

function adjustMargin(imageId) {
var image = document.getElementById(imageId);
image.setAttribute("style", "margin: 0 " + (300 - image.clientWidth / 2).toString() + "px");
}

可以看到不太好的工作示例here .

最佳答案

使用 CSS:

#imgId {
margin: 0 auto;
display: block;
// you are subtracting 300px and dividing by 2
// so assume your image is 300px wide
width: 300px;
}

img 标签是一个 inline 元素,因为 margin: 0 auto 仅适用于 block 元素,您必须包含 显示:在 img css 上阻止

居中 内联 元素的替代方法是:

#imgId {
text-align: center;
}

两种方法的演示 here

关于javascript - 在 Javascript 中设置 img 的边距,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13342771/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com