获取元素的css样式有三种方法

获取元素的css样式有三种方法

  1. ele.style
    返回CSSStyleDeclaration 类型的对象,只能获取内联样式,可读,可写
  2. window.getComputedStyle(el,null)
    返回CSSStyleDeclaration 类型的对象,可以获取内联,嵌入样式,外联样式,仅读
  3. document.defaultView.getComputedStyle(el,null)
    同window一样

获取样式

ele.style.backgroundColor
ele.style["background-color"]
ele.style.getPropertyValue('background-color')

window.getComputedStyle(el,null).backgroundColor
window.getComputedStyle(el,null)["background-color"]
window.getComputedStyle(el,null).getPropertyValue('background-color')

<style>
    .main{
        background-color: #f00;
    }
</style>

<div class="main" id="main" style="color:#000">
    内容
</div>

<button onclick="getStyle()">获取元素的样式</button>

<div id="show"></div>

<script>
    function getStyle(){
        var $main = document.querySelector('#main')
        var $show = document.querySelector('#show')

        var eleStyle = $main.style //返回CSSStyleDeclaration 类型的对象,只能获取内联样式,可读,可写
        var eleCss = window.getComputedStyle($main,null)//返回CSSStyleDeclaration 类型的对象,可以获取内联,嵌入样式,外联样式,仅读
        var eleCssView = document.defaultView.getComputedStyle($main,null); 

        console.log(document.defaultView === window) // true 

        console.log(eleStyle) 
        console.log(eleCss) 
        console.log(eleCssView) 

        console.log(eleStyle.backgroundColor) // undefined
        console.log(eleStyle.getPropertyValue('background-color')) // undefined
        console.log(eleStyle.getPropertyValue('color')) // rgb(0,0,0)

        console.log(eleCss.backgroundColor) // rgb(255,0,0)
        console.log(eleCss["background-color"]) // rgb(255,0,0)
        console.log(eleCss.getPropertyValue('background-color'))// rgb(255,0,0)

        console.log(eleStyle.width) // undefined
        console.log(eleCss.width) // 100px

        $show.innerHTML = eleStyle

    }
</script>
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。