javascript 样式操作以及代替方案

<div id="wrap">
    
</div>
var oWrap = document.getElementById("wrap");

使用js改变css样式表

  1. 外部样式表=> 不可以操作
  2. 内部样式表
  3. 行内样式
var oCss = document.getElementById("css");
//可以操作,但是要先手动去找出选择器的优先级,操作很麻烦,所以很少用这样的方式
oCss.innerText = "#wrap{width:50px;height:50px}";```
方法一
var oWrap = document.getElementById("wrap");
oWrap.style.width = "50px";
oWrap.style.height = "50px";
oWrap.style["background-color"] = "red";//background-color在js中-会报错
oWrap.style.backgroundColor = "red"; //可用驼峰式写法代替,-后的第一个字符大写
//-webkit-linear-gradient   => WebkitLinearGradient 

方法二
oWrap.style.width = "50px";
oWrap.style.height = "50px";
oWrap.style.backgroundColor = "red";
oWrap.style.position = "absolute";
oWrap.style.left = "100px";


oWrap.style. = "width:50px;height:50px;background-color:red;position:absolute;
				left:100px;";//可以这么写但不好
//加.cssText 
oWrap.style.cssText = 						"width:50px;height:50px;backgroundcolor:red;
position:absolute;left:100px;";
方法三

更好的代替方案

div#wrap{
    width: 100px;
    height: 100px;
    background-color: pink;
}
div#wrap.show{//把要改变的样式写好,用的时候加上show类名
    width: 50px;
    height: 50px;
    backgroundcolor: red;
	position: absolute;
    left: 100px;
}
var nClass = oWrap.className + " show";	//show前面记得加个空格
										//nClass=>new class
										//oWrap.className 获取原来有的class名 
oWrap.className = nClass;//加上类名
//合并
=> oWrap.className += " show";//只能加类名,不能减类名
方法四

classList

//HTML5标准下,DOM提供了一个新的操作class类名的API: classList

oWrap.classList.add("show");		//添加类名
oWrap.classList.remove("show");		//移除类名
//oWrap.style.float不能直接这么写,float是关键词
oWrap.style.cssFloat = "left";
oWrap.style.styleFloat = "left";
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值