1

我想知道是否可以确定HTML 元素的内联样式。我不需要检索该值,而只是检测它是否被设置为内联。

例如,如果 HTML 是:

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

如何确定width,heightbackground已明确声明为内联?

据我所知,该解决方案可以通过两种方式发挥作用。我可以询问它是否设置了特定属性,它会告诉我真假,或者它可以告诉我所有已设置的属性。像这样:

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 源代码。

谢谢

4

5 回答 5

3

更新为与 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;
}

因此,如果您有这样的元素:

<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
于 2009-01-24T22:12:35.323 回答
1

HTML 元素的 style 属性返回一个列出所有属性的样式对象。任何具有值(除了 null 或空字符串)的值都已在内联样式属性上设置。

于 2009-01-24T22:09:34.440 回答
0

您可能想尝试执行以下操作:

var obj = document.getElementById("foo");
var obj_has_background = (obj.style.background != "");
var obj_has_width = (obj.style.width != "");
var obj_has_height = (obj.style.height != "");

似乎有点长,但这是我能想到的最好(也是最短)的解决方案。

于 2009-01-24T22:13:03.577 回答
0

您是要检查某个样式属性是否存在,还是只想要一个可能的属性列表?如果您已经知道该属性,那么您可以使用

hasStyle(obj,'width');
function hasStyle(obj, style)
{
     switch(style)
         case 'width':
              return obj.style.width ? true : false;
         case 'background':
              return obj.style.background ? true : false;
}

您可以使用 Paolo 的函数来生成样式数组。

于 2009-01-24T22:51:35.807 回答
0

以下是两个返回本地元素样式定义的函数:

function getLocalStyle(pEleId, pStyle) {
    var camelStyle = camelCase( pStyle );
    var eleStyles = document.getElementById(pEleId).style
    return eleStyles[camelStyle];
}

function camelCase(str) {
  return str
    .split('-')
    .reduce((a, b) => a + b.charAt(0).toUpperCase() + b.slice(1));
}

用法:

var backgroundColor = getLocalStyle( pLayerName, "background-color" );
于 2020-07-04T20:59:24.440 回答