js改变css样式的三种方法

 

 

共用代码:

<div id="div">这是一个盒子</div>
var div = document.getElementById("div");

第一种:用cssText

div.style.cssText='width:600px;height:250px;border:1px red solid;text-align: center;line-height: 250px;';

第二种:用setProperty()

 div.style.setProperty('width','700px');
 div.style.setProperty('height','300px');
 div.style.setProperty('line-height','300px');
 div.style.setProperty('background','#f00');
 div.style.setProperty('color','#fff');
 div.style.setProperty('border','1px solid blue');
 div.style.setProperty('text-align','center');

第三种:使用css属性对应的style属性

复制代码
 div.style.width = "800px";
 div.style.height = "250px"; 
 div.style.lineHeight = "250px"; 
 div.style.background = "#000";
 div.style.color = "#fff";
 div.style.border = "1px solid #111";
 div.style.textAlign = "center";
复制代码

 

复制代码
<body>
        <div id="div">这是一个盒子</div>
        <script type="text/javascript">
            var div = document.getElementById("div");
            
            //第一种:用cssText
            div.style.cssText='width:600px;height:250px;border:1px red solid;text-align: center;line-height: 250px;';
            
            //第二种:用setProperty()
            div.style.setProperty('width','700px');
            div.style.setProperty('height','300px');
            div.style.setProperty('line-height','300px');
            div.style.setProperty('background','#f00');
            div.style.setProperty('color','#fff');
            div.style.setProperty('border','1px solid blue');
            div.style.setProperty('text-align','center');
            
            //第三种:使用css属性对应的style属性
            div.style.width = "800px";
            div.style.height = "250px"; 
            div.style.lineHeight = "250px"; 
            div.style.background = "#000";
            div.style.color = "#fff";
            div.style.border = "1px solid #111";
            div.style.textAlign = "center";
        </script>
    </body>
复制代码

 

转载于:https://www.cnblogs.com/lydg/p/11363810.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值