# 修改css样式

const el = document.createElement('div')

el.style.backgroundColor = 'red'
// 或者 
el.style.cssText = 'background-color: red'
// 或者
el.setAttribute('style', 'background-color: red')

直接在.style对象上设置样式属性将需要使用驼峰式命名作为属性键,而不是使用短横线命名。 如果需要设置更多的内联样式属性,则可以通过设置.style.cssText属性,以更加高效的方式进行设置 。 但是cssText设置后原先的css样式被清掉了,因此,要把之前需要保留的样式还得重写写一遍。( 如果是在style标签写的内容,可以保留 )

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8" />
		<meta name="viewport" content="width=device-width, initial-scale=1">
		<title></title>
		<style>
			h1{
				color:blue
			}
		</style>
	</head>
	<body>
		<h1>333</h1>
	</body>
</html>
<script type="text/javascript">
let h1 =document.getElementsByTagName("h1")[0]
h1.style.color="red";
h1.style.fontStyle='italic';
h1.setAttribute('style', 'background-color: red')
h1.style.cssText="font-size:100px";
</script>
let h1 =document.getElementsByTagName("h1")[0]
h1.style.color="red";
h1.style.fontStyle='italic';
h1.setAttribute('style', 'background-color: red')
//h1.style.cssText="font-size:100px";
最后更新: 12/11/2019, 12:58:28 PM