一.获取属性
<
div
style=
"width: 100px; height: 100px; background-color:red;"
></
div
>
<
script
type=
"text/javascript"
>
var
div=
document.
getElementsByTagName(
"div")[
0];
<
/
script
>
但是这样只能读和写行间样式表,如果单独创建一个css文件就读不到了
二.查询计算
这样获取的是最终的属性,而不是只是获取行间样式表种的属性
这个只能是读取,不能通过这个方法改变属性值
扫描二维码关注公众号,回复:
1935210 查看本文章
这个方法只有IE浏览器存在,但是我们通过封装方法可以解决兼容性问题:
var
div=
document.
getElementsByTagName(
"div")[
0];
var
getStyle=
function(
elem,
prop){
if(
window.
getComputedStyle(
elem,
null)){
//elem是标签,prop是属性
return
window.
getComputedStyle(
elem,
null)[
prop];
}
else{
return
elem.
currentStyle[
prop];
}
}
这样就可以获取属性了
另外
getcomputedStyle(elem,null)里面的null就是获取伪元素的,就像这样子:
div::before{
width:
50px;
height:
45px;
background-color:
aqua;
display:
inline-block;
}
var
div=
document.
getElementsByTagName(
"div")[
0];
这样就能读取伪元素里面的属性值,但是不能改变这个值
小实验:
这个例子实现了小方块自动向右移动的方法
<
div
style=
"width: 100px; height: 100px; background-color:red;position: absolute;left: 0px;"
></
div
>
<
script
type=
"text/javascript"
>
var
div=
document.
getElementsByTagName(
"div")[
0];
//封装getstyle()方法
var
getStyle=
function(
elem,
prop){
if(
window.
getComputedStyle(
elem,
null)){
return
window.
getComputedStyle(
elem,
null)[
prop];
}
else{
return
elem.
currentStyle[
prop];
}
}
setInterval(
function(){
div.
style.
left=
parseInt(
getStyle(
div,
"left"))+
1+
"px";
},
100);
<
/
script
>
提醒一下,因为:
因为这个输出是带有px的,所以我们要用parseInt()方法去掉“px”