js动态改变css样式

  • 动态改变页面元素样式:
  1. 使用getElement系列方法访问元素。
  2. 改变样式属性:style属性;className属性。
<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
		<script type="application/javascript" src="js/动态改变css.js"></script>
		<style type="text/css">
			.menu{
				width: 100px;
				height: 30px;
				border-top-left-radius:10px ;
				border-top-right-radius: 10px;
				background-color: darkgray;
				text-align: center;
				padding-top: 4px;
			}
			
			.menuOver{
				background-color: orange;
				width: 100px;
				height: 30px;
				border-top-left-radius:10px ;
				border-top-right-radius: 10px;
				text-align: center;
				padding-top: 4px;
			}
			
			.menuOut{
				background-color: darkgray;
				width: 100px;
				height: 30px;
				border-top-left-radius:10px ;
				border-top-right-radius: 10px;
				text-align: center;
				padding-top: 4px;
			}
			
			.first_ul{
				list-style: none;
				
			}
			
			.first_ul li{
				float: left;
				background-color: #F79337;
				font-size: 14px;
				font-weight: bold;
				color: white;
				border-radius: 5px;		
				width: 70px;
				height: 30px;
				text-align: center;	
				padding-top: 10px;	
			}
			
		</style>
	</head>
	
	<body>
		<!--修改css样式,单击:onclick-->
		<div id="content1">DIV样式</div>
		<input type="button" name="" id="" value="改变样式" οnclick="btn1()";/>
		<hr />
		<!--鼠标移入onmouseover移出onmouseout鼠标按钮按下-->
        <div id="menuObj" class="menu" οnmοuseοver="setMenuBgColor(this,1)"; οnmοuseοut="setMenuBgColor(this,2)";>
        	商品类别
        </div>
        <hr />
        <!--同时改变所有li的样式-->
        <ul class="first_ul">
        	<li>首页</li>
        	<li>家用电器</li>
        	<li>手机数码</li>
        	<li>日用百货</li>
        	<li>书籍</li>
        </ul>
	</body>
</html>
function btn1(){
	/*
	 * 改变div元素背景
	 * 元素中间横线去掉,第二个首字母也大写
	 */
	document.getElementById("content1").style.backgroundColor="red";
}

//利用obj参数传入this可以使方法复用
function setMenuBgColor(obj,flag){
	switch(flag){
		case 1:
//			1.通过对象中的style属性来修改css样式效果
//			鼠标移入
//			document.getElementById("menuObj").style.backgroundColor="orange";
//			obj.style.backgroundColor="orange";
//			2.通过类选择器来修改CSS样式效果
			obj.className = "menuOver";		//只需要加样式名,不用.
			break;
		case 2:
//			鼠标移出
//			document.getElementById("menuObj").style.backgroundColor="darkgray";
//			obj.style.backgroundColor="darkgray";		
			obj.className = "menuOut";
			break;
	}
}

window.οnlοad=function(){
//	同时改变所有li的样式
	var objli=document.getElementsByTagName("li");
	for (var i=0;i<objli.length;i++) {
		objli[i].οnmοuseοver=function(){
			this.style.backgroundColor="red";
		}
		objli[i].οnmοuseοut=function(){
			this.style.backgroundColor="#F79337";
		}
	}
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值