美文网首页
获取元素的css样式有三种方法

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

作者: 一路坚挺 | 来源:发表于2020-07-25 22:57 被阅读0次

获取元素的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>

相关文章

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

    获取元素的css样式有三种方法 ele.style返回CSSStyleDeclaration 类型的对象,只能获取...

  • 从零玩转jQuery-CSS操作

    jQuery操作CSS样式 css(name|pro|[,val|fn])方法用于设置或获取元素CSS样式格式1:...

  • 获取元素大小和位置的五种方式

    一、直接获取元素样式属性值 运用之前在JS如何获取元素样式?这篇文章中提到的三种获取元素样式方法便可获取元素大小和...

  • JS工具类函数封装

    根据id获取元素 获取css样式 通过标签名获取元素 通过class获取元素 运动函数 类数组转数组方法 获取n-...

  • js

    ##获取css设置的元素样式的方法 chrome FF vardiv=document.getElementByI...

  • jQuery获取设置样式

    css();方法 获取或设置样式 对以下html标签进行样式的获取和设置 获取样式 css();方法设置参数,...

  • JavaScript获取元素计算后样式的封装

    getComputedStyle方法获取的是最终应用在元素上的所有CSS属性对象(计算后样式的集合)。只能获取样式...

  • jQuery元素的操作

    样式操作样式的设置 css方法操作的是元素的行内样式//css方法// $('#test').css('backg...

  • 前端学习Day 6

    css 层叠样式表 一、三种css样式使用方式 1.内联样式将css的样式直接用在页面元素中,直接作用于这个元素。...

  • 前端笔记汇总

    JQuery获取元素 获取id为countryId的元素的值 css 使用class 和id调用样式 样式代码 调...

网友评论

      本文标题:获取元素的css样式有三种方法

      本文链接:https://www.haomeiwen.com/subject/tmmmlktx.html