【问题标题】:how can I detect the css value with jquery? [duplicate]如何使用 jquery 检测 css 值? [复制]
【发布时间】:2014-04-10 05:55:18
【问题描述】:

假设在我的样式表中:

.test{width: 20px; height: 50px; color: blue;}
.some-test{padding: 20px; margin: 10px;}
.even-test{font-size: 20px; color: red;}

是否可以检测每个 css 属性的 20px 值以便我可以替换它?


我想检测到这样的事情:

$('.selector').filter(function() {
    return $(this).css(property) === '20px';
}).css(property, value);

有没有类似:style.arguments[] 的东西?

【问题讨论】:

  • .css() - 谷歌是你的朋友。这适用于给定此类的元素。
  • 不过,只有在元素被赋予了这样的类后,您才能检测到它。
  • 您不能使用 jQuery 调整样式表中的值
  • @Mr.iC 您正在指定属性,而他想根据属性值检测属性
  • @Mr.Alien 没错——一定有更简单的方法。有趣的问题..

标签: javascript jquery


【解决方案1】:

通过 CSS 样式搜索(不确定这是否获得 style="..." 样式):

var parseStyle = function(rules) {
    for (var i = 0; i < rules.length; ++i)
    {
        console.log(rules[i].style.width);
    }
};

//care needs to be taken as to when this executes - styles may not have been loaded yet
for (var i = 0; i < document.styleSheets.length; ++i)
    if (document.styleSheets[i].rules && document.styleSheets[i].rules.length > 0)
        parseStyle(document.styleSheets[i].rules);

如果不是您想要的 CSS 属性,而是元素样式的结果,这可能是您所追求的更多...

var element = ... jquery or whatever
var elementStyle = element.currentStyle || getComputedStyle(element);
console.log(elementStyle.width);

【讨论】:

    【解决方案2】:

    您可以使用 jQuery 中的过滤器功能来查找具有该宽度的所有元素。

    $('.allYourSelectors').filter(function() {
        return $(this).css('width') === '20px';
    }).css("width", newWidth);
    

    但是,最好只为它们提供所有可以修改的相同类。

    【讨论】:

    • 这只是宽度,但我想检测每个属性的值。
    • @C-link 那么你就必须像上面那样做多个语句。
    • this.style.width 并避免在jQuery中包装元素的开销不是更好吗?
    猜你喜欢
    • 2014-02-17
    • 1970-01-01
    • 2013-12-04
    • 2014-09-21
    • 2011-10-14
    • 2012-07-07
    • 1970-01-01
    • 2012-05-12
    相关资源
    最近更新 更多