JS之脚本化CSS

1、读写元素css属性

dom.style.prop  //只有这个可以写入
  • 可以读写行间样式,没有兼容性问题,碰到float这样的保留字属性,前面应该加css。eg:float->cssFloat
  • 复合属性必须拆解,组合单词变成小驼峰式写法  background-color ->backgroundColor
  • 写入的值必须是字符串格式

2、查询计算样式

window.getComputedStyle(ele,null)
  • 获取的是 当前元素的所有css展示值 包括默认值  ,null可以获取伪元素
  • 计算样式只读
  • 返回的计算样式的值都是绝对值,没有相对单位
  • IE8及以下不兼容(dom.currentStyle
    只能获取,不能修改,返回的计算样式的值不是经过转换的绝对值,IE独有属性)

3、获取伪元素的样式表

<!DOCTYPE  html>
	<html lang="en">
	<head>
		<meta charset="UTF-8">
		<title>demo</title>
		<link rel="stylesheet" href="./src/demo.css">
	<style type="text/css">
		div{
			width:100px;
			height: 100px;
			background-color: red;
		}
		.active{
			width:200px;
			height: 200px;
			background-color: green;
		}
		/*div::after{
			content: "";
			width:50px;
			height: 50px;
			background-color: green;
			display: inline-block;

		}
	</style>
	</head>
<body>
    <script type = "text/javascript>
//点击这个div点击一次就会变成宽200高200背景颜色为green的
    var div = document.getElementsByTagName('div')[0];
	div.onclick = function(){
		// div.style.width = "200px";
		// div.style.height = "200px";
		// div.style.backgroundColor = "red";
		div.className = "active";
	}
    </script>
</body>
</html>

4、让方块运动

<!DOCTYPE  html>
	<html lang="en">
	<head>
		<meta charset="UTF-8">
		<title>demo</title>
		<link rel="stylesheet" href="./src/demo.css">
	<style type="text/css">
	</style>
	</head>
<body>
	<div style="width:100px;height: 100px;background-color: red;position: absolute;left: 0;top: 0;"></div>
	<script type="text/javascript">
	function getStyle(elem,prop){
		if(window.getComputedStyle){
			return window.getComputedStyle(elem,null)[prop];

		}else{
			return elem.currentStyle[prop];
		}
	}
	var div = document.getElementsByTagName('div')[0];
	// 让方块移动
	var timer= setInterval(function(){
		div.style.left = parseInt(getStyle(div,'left')) + 10 +'px';  //
		if(parseInt(div.s每次移动之前都要知道方块当前的位置和我们想让他移动的距离tyle.width) > 1000) {
			clearInterval(timer);   //停止运动
		}
	},100);
	</script>
</body>
</html>

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值