2.2、封装一个获取元素的样式的方法

一、设置和获取行内的样式

<div id="box"></div>
<script>
    //设给元素置样式  (注意这设置的是行内样式)
    var obox = document.getElementById('box')
    obox.style.width = '200px';
    obox.style.height = '200px';
    obox.style.background = 'red'

    // 获取  (带单位,且只能获取行内的样式)
    console.log(obox.style.width) //200px
    console.log(obox.style.height) //200px
    console.log(box.style.background) //red
</script>
这种方式只能获取行内的样式

二、style内的样式的获取
用getComputedStyle(元素).width 这种方法既可以获取style内的也可以获取行内的

<div id="box" style="width: 100px"></div>
<script>
    var obox = document.getElementById('box')
        // getComputedStyle(元素).样式名  这个方法得到计算以后的元素的样式 行内和style里的都能得到
    console.log(getComputedStyle(obox).width) //200px带单位
    console.log(getComputedStyle(obox).height) //200px带单位
    console.log(getComputedStyle(obox).background) //rgb(255, 0, 0) none repeat scroll 0% 0% / auto padding-box border-box
    console.log(getComputedStyle(obox).backgroundColor) //rgb(255, 0, 0)
</script>

//但是有兼容性问题 IE8及以下没有 用
元素.currentStyle.样式名

封装方法


```csharp
  <div id="box" style="width: 100px"></div>

    <script>
        var obox = document.getElementById('box')

        // 这个方法用于获取元素的样式
        // 传几个参数 1.目标  2.样式
        //兼容IE8及以下
        function getStyle(obj, attr) {
            //判断是否有这个函数,没有会返回undefined
            if (typeof(getComputedStyle) == 'function') {
                // IE9及以上
                return getComputedStyle(obj)[attr]
                    //为什么不是点呢  因为.就把attr变成了字符串 所以用[]形式
            } else {
                // IE8及以下
                return obj.currentStyle[attr]
            }
        }
        console.log(getStyle(obox, 'width'))

 	
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值