[英]How to align an image to the center using Javascript?
原谅我,我还是 Javascript/HTML/PHP 的新手。 在我的 HTML 代码中,我引用了文件 DisplayImage.js 中的 JavaScript 函数:
<body>
<div id="display_image" align="center">
<script type="text/javascript" src="DisplayImage.js"></script>
</div>
</body>
DisplayImage.js JavaScript 代码的一部分是:
function show_image(src, width, height, alt) {
var img = document.createElement("img");
img.src = src;
img.width = width;
img.height = height;
img.alt = alt;
document.body.appendChild(img);
}
show_image("sample1.jpg", 900, 690, "sample image #1");
这个 JS 函数只显示我想要传递到我的页面上的任何图像。 我的问题是,它总是左对齐。 我希望图像在中心对齐。 我尝试将 align="center" 放入 HTML 代码中的 div 标记中,但这不起作用,所以我假设您需要从 JS 函数中执行此操作。
谁能帮我使图像在这里居中对齐?
添加行img.style.margin = "0 auto";
应该做的伎俩。
正如其他人提到的,使用“margin: 0 auto;” 在 img 标签上。 不过图片需要设置为“display:block;”
#display_image > img {
display: block;
margin: 0 auto;
}
您可以使用 CSS 样式标签修改您的 div。
<div id="display_image" style="display:block; margin:0 auto;">
<script type="text/javascript" src="DisplayImage.js"></script>
</div>
如果您要修改不止一个实例,请更改您的 CSS(嵌入式或外部文件)
<!DOCTYPE html>
<head>
<style>
img.center {
position: absolute;
top: 50%;
bottom: 50%;
left: 50%;
right: 50%;
margin: auto;
}
</style>
<script>
function ex() {
var x = document.createElement("IMG")
x.setAttribute("class", "center")
x.setAttribute("src", "example.png");
x.setAttribute("width", "50");
x.setAttribute("height", "50");
x.setAttribute("alt", "example");
document.body.appendChild(x);
}
</script>
</head>
<body>
<button onclick="ex()">click</button>
</body>
</html>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.