具有多个可能值的CSS规则(jQuery)

Yan*_*hon 13 javascript css jquery

问题很简单; 使用jQuery的css函数,可以返回CSS属性的计算样式,但是如果要呈现的属性有多个样式呢?例如 :

<div id="foo" style="text-decoration:underline;">Some underline text</div>
Run Code Online (Sandbox Code Playgroud)

指令$('#foo').css('text-decoration');将返回underline.现在如果我改成它

<div id="foo" style="text-decoration:underline;">Some underline <span id="bar" style="text-decoration:line-through;">text</span></div>
Run Code Online (Sandbox Code Playgroud)

该指令$('#bar').css('text-decoration');将返回line-through,好吧.

但实际的文字也是 underline!我怎么能两个都回来?如果我想知道某些文本是否同时存在underline,我是否需要搜索所有祖先line-through?听起来有点痛苦,不是吗?

**编辑**

这个HTML出现了另一个问题

<span style="text-decoration:underline;">some <span id="e1" style="font-weight:bold;">text</span></span>
Run Code Online (Sandbox Code Playgroud)

由于某种原因$('#e1').css('text-decoration');返回none的地方,而文字清楚地用下划线呈现.

**免责声明**

这个问题不是讨论UA如何呈现元素,而是元素层次结构是否应用CSS.如果一个人想要text-decoration更好地理解,我建议人们会读到它.这个问题试图关注更广泛的问题.例如,它也可以应用于此HTML

<div style="display:none;">Some <span id="keyword" style="text-decoration:underline;">hidden</span> text</div>
Run Code Online (Sandbox Code Playgroud)

人们可能想知道元素keyword是否可见.使用下面的代码,这很简单

cssLookup($('#keyword'), 'display', 'none');   // -> true
Run Code Online (Sandbox Code Playgroud)

**更新**

在所有答案和评论之后,基于Brock Adams解决方案:

/**
 * Lookup the given node and node's parents for the given style value. Returns boolean
 *
 * @param e     element (jQuery object)
 * @param style the style name
 * @param value the value to look for
 * @return boolean
 */  
function cssLookup(e, style, value) {
    var result = (e.css(style) == value);
    if (!result) {
        e.parents().each(function() {
            if ($(this).css(style) == value) {
                result = true;
                return false;
            }
        });
    }

    return result;
}
Run Code Online (Sandbox Code Playgroud)

谢谢大家的意见.

Bro*_*ams 2

我认为没有任何浏览器或 W3C 提供了实现此目的的好方法。

一个复杂的因素是了解哪些样式取消了前面的样式(例如,下划线与无下划线)。

因此,我们需要多个查找表或人工判断才能知道实际应用了哪种样式。

最后,所有这些方法(到目前为止有 3 个答案)无法区分空白或缺失的样式设置和显式设置none。显然,浏览器可以none以不同于空白或缺失设置的方式呈现显式设置。

对于人类使用,这段代码应该可以解决问题:

function cssTree (jNode, styleName, bShowBlanks) {
    var styleArray  = [jNode.css (styleName)];

    jNode.parents ().map ( function () {
        var style   = $(this).css (styleName);

        if (bShowBlanks  ||  ! /^(none|\s*)$/i.test (style) )
            styleArray.push (style);
    } );
    return styleArray;
}

alert ( cssTree ( $("#bar"), 'text-decoration') );
Run Code Online (Sandbox Code Playgroud)


在 jsFiddle 上查看它的实际效果。

结果:

bar: line-through,underline
el: none,underline

//-- With bShowBlanks = true.
bar: line-through,underline,none,none
el: none,underline,none,none
Run Code Online (Sandbox Code Playgroud)