<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
div{
color:yellow;
}
</style>
</head>
<body>
<div style="width:100px;height:100px;background-color:red">This is div</div>
</body>
</html>
<script>
var div = document.getElementsByTagName("div")[0];
console.log(div.style.color); //""
console.log(div.style.backgroundColor); //red
</script>
<script>
var div = document.getElementsByTagName("div")[0];
div.style['background-color'] = "green";
console.log(div.style.backgroundColor); //green
</script>
<script>
var div = document.getElementsByTagName("div")[0];
var styleObj = window.getComputedStyle(div,null);
console.log(styleObj.backgroundColor); //red
console.log(styleObj.color); //yellow
</script>
<script>
var div = document.getElementsByTagName("div")[0];
var styleObj = div.currentStyle;
console.log(styleObj.backgroundColor); //red
console.log(styleObj.color); //yellow
</script>
<script>
//获取非行间样式(style标签里的样式或者link css文件里的样式),obj是元素,attr是样式名
function getStyle(obj,attr){
//针对IE
if(obj.currentStyle){
return obj.currentStyle[attr]; //由于函数传过来的attr是字符串,所以得用[]来取值
}else{
//针对非IE
return window.getComputedStyle(obj,false)[attr];
}
}
/*
获取或者设置css属性
*/
function css(obj,attr,value){
if(arguments.length == 2){
return getStyle(obj,attr);
}else{
obj.style[attr] = value;
}
}
</script>
<style>
div{
width:200px;
height:200px;
background-color:#FC9;
font-size:20px;
text-align:center;
}
div:after{
content:"This is after";
display:block;
width:100px;
height:100px;
background-color:#F93;
margin:0 auto;
line-height:50px;
}
</style>
<body>
<div id='myDiv'>
This is div
</div>
<input id='btn' type="button" value='getStyle'/>
<script>
var btn = document.querySelector('#btn');
btn.onclick = function(){
var div = document.querySelector('#myDiv');
var styleObj = window.getComputedStyle(div,'after');
console.log(styleObj['width']);
}
</script>
</body>
<script>
var div = document.getElementsByTagName("div")[0];
var styleObj = window.getComputedStyle(div,null);
console.log(styleObj.getPropertyValue("background-color"));
</script>
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有