栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

使用JavaScript读取元素的CSS属性

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

使用JavaScript读取元素的CSS属性

您有两种选择:

  1. 手动枚举和解析
    document.styleSheets
    对象(不建议使用,除非您要获取由某个选择器定义的所有特定样式属性)。
  2. 创建与选择器匹配的元素,然后使用
    getComputedStyle
    currentStyle
    (IE)方法获取属性值。

在你的榜样,试图得到一定的属性(比如说:

color
)有一个div

function getStyleProp(elem, prop){    if(window.getComputedStyle)        return window.getComputedStyle(elem, null).getPropertyValue(prop);    else if(elem.currentStyle) return elem.currentStyle[prop]; //IE}window.onload = function(){    var d = document.createElement("div"); //Create div    d.className = "layout";     //Set class = "layout"    alert(getStyleProp(d, "color"));       //Get property value}

关于您的问题的评论 ,另一个函数:
下面的函数将忽略当前元素的内联样式定义。如果您想知道从样式表继承的样式定义(不包含父元素的继承样式定义),请遍历树并临时擦除

.cssText
属性,如以下功能所示:

function getNonInlineStyle(elem, prop){    var style = elem.cssText; //Cache the inline style    elem.cssText = "";        //Remove all inline styles    var inheritedPropValue = getStyle(elem, prop); //Get inherited value    elem.cssText = style;     //Add the inline style back    return inheritedPropValue;}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/615166.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号