通过JavaScript中的CSS属性选择元素
作者:互联网
是否可以通过CSS属性选择DOM元素?
例如:
awsome_function ({'background-color' : '#0cf'});
// return all object, which's background-color css attribute value is '#0cf'
awsome_function (['background-color']);
// return all object, which has background-color css attribute
awsome_function (['-my-special-cssattribute'])
// return all object, which has '-my-special-cssattribute' css attribute
我知道可以使用jQuery每个方法来选择元素,如下所示:
$('*').each(function(){
if($(this).css('-my-special-cssattribute')) {
/* do something */
}
})
但是,它可能很慢且毫无意义.有更酷的方法吗?
解决方法:
我会使用自定义选择器:
$.extend($.expr[":"], {
foo: function (e) {
return $(e).css('background-color') == '#0cf';
}
});
用法:
alert($('div:foo').size()); //get the count of all the divs that matches the selector
标签:jquery-selectors,css,javascript,jquery 来源: https://codeday.me/bug/20191101/1985145.html