js 操作元素样式style、类名class

操作样式

**操作html的style属性中的样式**
	添加样式
	
		对象名.style.去掉样式中的-,并-后的首字母为大写
			showdiv.style.backgroundColor="red";
		当操作的css样式是js中的关键字时,需要在样式名前加css
			showdiv.style.cssFloat="left";
			
	一次性添加多个样式
			showdiv.style.cssText="height:80px;weight:40px;color:red;background-color:blue";
			
	删除样式
	
		将样式值赋为空,就近原则,若标签中有style属性,css代码域中有属性,则会先将标签中style属性为空,显示css中属性
			showdiv.style.backgroundColor="";
			
	修改样式
		和添加样式相同
			showdiv.style.border="solid 2px orange";


**通过类选择器className**

	添加修改样式,首先在标签中声明class="类选择器名"
		对象名.className=另一个类选择器名
			<div id="div01" class="common"></div>
			div01.className="common2";
		
		方式二:
			div.classList.add(样式1,样式2,...);
			div.classList.toggle(样式名,布尔值);  true添加/false移出
			
	删除样式
		对象名.className="";
		div.clssList.remove(样式1,样式2,...);

代码示例:

<html>
	<head>
		<title>js 操作元素样式</title>
		<meta charset="utf-8"/>
		<script type="text/javascript">
			function t1()
			{
				var showdiv=document.getElementById("showdiv");
				
				showdiv.style.backgroundColor="red";
				showdiv.style.border="solid 2px orange";
				showdiv.style.backgroundColor="";
			}
			
			function t2()
			{
				var div01=document.getElementById("div01");
				
				alert(div01.className);
				div01.className="common2";
				div01.className="";
			}
			
			
		</script>
		<style type="text/css">
			#showdiv{
				width:200px;
				height:200px;
				border:solid 1px;
			}
			.common{
				width:200px;
				height:200px;
				border:solid 1px;
			}
			.common2{
				width:200px;
				height:200px;
				border:solid 1px;
				background-color: orange;
			}
		</style>
	</head>
	<body>
		<input type="button" value="添加样式" onclick="t1()"/>
		<input type="button" value="className方式" onclick="t2()"/>
		<hr />
		<div id="showdiv">
			
		</div>
		
		<div id="div01" class="common">
			
		</div>
	</body>
</html>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值