有关获取元素、浏览器兼容的应用!!

获取元素的样式

第一种:style

1.语法:HTML元素.style.样式属性;
2.示例:
alert(document.getElementById("cartList").display);
3.适用:所有浏览器都兼容但是只可以获取行内css样式的数据

第二种:getComputedStyle

1.语法:document.defaultView.getComputedStyle(元素,null).属性;
2.示例:
var cartList=document.getElementById("cartList"); alert(document.defaultView.getComputedStyle(cartList,null).display);
3.适用:火狐和谷歌支持但是低版本IE无效

第三种:currentStyle

1.语法:HTML元素. currentStyle.样式属性;
2.示例:
alert(document.getElementById("cartList").currentStyle.display);
3.适用:火狐谷歌不支持 但是IE兼容

每一种都有或多或少的不完美兼容性,但是我们要让每个浏览器都兼容的话要怎么办呢!

兼容火狐、谷歌、IE的方式

使用currentStyle来测试使用的浏览器然后使用对应的代码!
示例:
var cartList=document.getElementById("cartList"); var ku; if(cartList.currentStyle){ ku=cartList.currentStyle.width; }else{ ku=document.defaultView.getComputedStyle(cartList,null).width;}

示例代码:
<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title>获取css</title>
    <style>
        div{
            height: 100px;
            width: 600px;
            background-color: red;
        }
    </style>
</head>
<body>
<div id="cs" onclick="show()">这是最最最普通的一个div</div>
<script>
    function show(){
        //获取div
        var div=document.getElementById("cs");
        //弹出div的相关的css属性的赋值
        //1.使用style:所有浏览器都兼容+只可以获取行内css样式的数据
        //alert(div.style.width);
        //2getComputedStyle:火狐和谷歌支持但是低版本IE无效
        /*var kuan1=document.defaultView.getComputedStyle(div,null).width;
        alert(kuan1);*/
        //3.使用currentStyle:火狐谷歌不支持 但是IE兼容
        /*var kuan2=div.currentStyle.width;
        alert(kuan2)*/
        //兼容火狐、谷歌、IE的方式
        var kuan3;
        //currentStyle:测试用户使用的浏览器   true:IE     false:火狐谷歌
        if(div.currentStyle){
            kuan3=div.currentStyle.width;
        }else{
            kuan3=document.defaultView.getComputedStyle(div,null).width;
        }
        alert(kuan3);
    }
</script>
</body>
</html>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值