如何读取元素的内联样式? [英] How to read inline styling of an element?

查看:193
本文介绍了如何读取元素的内联样式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

多么幸福。我想知道是否可以确定内嵌样式是否属于HTML元素。

Howdy all. I'd like to know if it's possible to determine what inline styling has been attributed to an HTML element. I do not need to retrieve the value, but rather just detect if it's been set inline or not.

例如,如果HTML是:

For instance, if the HTML were:

<div id="foo" style="width: 100px; height: 100px; background: green;"></div>

如何确定width,height和background ,inline?

How can I determine that "width," "height," and "background" have been explicitly declared, inline?

据我所知,解决方案可以工作两种方式。我可以问它是否设置了一个特定的属性,它会告诉我true或false,或者它可以告诉我已经设置的所有属性。像这样:

As far as I can tell, the solution can work two ways. I can ask it if a specific attribute is set and it will tell me true or false, or it can tell me all attributes that have been set. Like so:

var obj = document.getElementById('foo');
obj.hasInlineStyle('width');  //returns true;
obj.hasInlineStyle('border'); //returns false;

//or

obj.getInlineStyles();   //returns array with values:
                       // 'width' 'height' and 'background'

我不感兴趣的css属性,通过声明在样式表,只有内联样式继承。最后,我无法控制HTML源代码。

I'm not interested in css attributes that are inherited via declarations in a stylesheet, only inline styles. One last thing, I have no control over the HTML source.

感谢

推荐答案

更新为使用IE

您可以尝试这样

function hasInlineStyle(obj, style) {
    var attrs = obj.getAttribute('style');
    if(attrs === null) return false;
    if(typeof attrs == 'object') attrs = attrs.cssText;
    var styles = attrs.split(';');
    for(var x = 0; x < styles.length; x++) {
        var attr = styles[x].split(':')[0].replace(/^\s+|\s+$/g,"").toLowerCase();
        if(attr == style) {
            return true;
        }
    }
    return false;
}

所以如果你有这样的元素:

So if you have an element like this:

<span id='foo' style='color: #000; line-height:20px;'></span>

这样也有一个样式表:

#foo { background-color: #fff; }

函数将返回...

var foo = document.getElementById('foo');
alert(hasInlineStyle(foo,'color')); // true
alert(hasInlineStyle(foo,'background-color')); // false

这篇关于如何读取元素的内联样式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆