javascript如何设置图片居中

2022-01-19 11:59:18 IT技术网 互联网
浏览

方法:1、用p和span包裹图片;2、用setAttribute()给其添加“display:table;text-align:center”和“display:table-cell;vertical-align:middle;”样式。

本教程操作环境:windows7系统、javascript1.8.5版、Dell G3电脑。

javascript设置图片居中的方法:

搭建一个HTML框架

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<style>
			p {
				width: 500px;
				height: 200px;
				border: green solid 1px;
			}
		</style>
	</head>
	<body>

		<p id="app">
			<span id="img">
				<img src="img/1.jpg" width="200" />
			</span>
		</p>
	</body>
</html>

1.png

使用setAttribute()方法添加图片居中样式

var p=document.getElementById("app");
var img=document.getElementById("img");
p.setAttribute("style","display:table;text-align: center;");
img.setAttribute("style","display:table-cell;vertical-align: middle;");

2.png

【相关推荐:javascript学习教程

以上就是javascript如何设置图片居中的详细内容,更多请关注dnjidi.com其它相关文章!