通过JS给div元素设置样式的几种方法

一、style

<div></div>

//js部分
<script>
	var oDiv = document.querySelector("div");

	//第一种方法:分别添加属性
	oDiv.style.width = "200px";
	oDiv.style.height = "200px";
	oDiv.style.background = "red";

	//第二种方法:合并添加属性
	oDiv.style.cssText = "width:200px;height:200px;background:red";
</script>

二、className

//通过为标签添加类名添加样式
//css部分
<style>
	.current{
		width:200px;
		height:200px;
		background:blue;
	}
	.mt60{
		margin-top:60px;
	}
</style>
	
//js部分
<script>
	oDiv.className = "current mt60";
</script>

猜你喜欢

转载自blog.csdn.net/xiamoziqian/article/details/85051947