我尝试用 google 搜索“jquery 函数返回具有类的 css 属性的对象”,但没有找到有值(value)的结果。
假设在 DOM 中我有一个 className =“A B C”的 div 节点。 我有一个名为“search”的有效 Jquery 对象,其中包含 html 元素。我需要查明它是否包含一些样式和值,如果我发现它们,我将执行一个操作(从 node.className 中删除该类)
var search = $("div.A");
var css_arr = search.prop("className").split(" ");
以下是要测试的样式的条件:
float != "none" or Float != "" -> if yes, remove the class
position != "absolute" or position != "" -> if yes, remove the class
left is present ... remove the class -> if yes, remove the class
top is present ... remove the class -> if yes, remove the class
我的问题是如何进行测试?
JQuery中有没有函数可以返回具有指定类的css属性的对象?
编辑: 我已经开始根据工作表对象的读取来编写代码。
cssList = function(node) {
var sheets = document.styleSheets, o = {};
var sheet;
for (var i in sheets) {
if ( sheets[i].hasOwnProperty('cssRules') )
sheet = sheets[i].cssRules;
else
if ( sheets[i].hasOwnProperty('rules') )
sheet = sheets[i].rules;
else
continue;
var rules = sheets[i].rules || sheets[i].cssRules;
for (var r in rules) {
if (node.is(rules[r].selectorText))
{
o = $.extend(o, make_it_easy.easy.css2json(rules[r].style), css2json(node.attr('style')));
}
}
}
return o;
}
此处存在问题:sheets[i].hasOwnProperty('cssRules')
或 sheets[i].hasOwnProperty('rules')
始终返回 false。为什么?在调试器中,我看到 cssRules 属性,但无法检查它是否存在。
最佳答案
jQuery 的克隆元素正在获取默认样式,我们可以这样使用它:
$.fn.extend({
removeClassWithStyles: function(properties) {
function filterClasses(child, cloned) {
var thisClassAttr = child.attr("class");
if (thisClassAttr) {
var splitClassName = thisClassAttr.split(/\s+/);
$.each(splitClassName, function(c, className) {
cloned.removeClass(className);
$.each(properties, function(p, prop) {
if (child.css(prop) != cloned.css(prop)) {
console.log('remove class: ' + className);
child.removeClass(className);
return false;
};
});
});
};
};
return this.each(function() {
var thisElement = $(this);
thisElement.find('*').each(function(e) {
var child = $(this);
var cloned = $(this).clone();
filterClasses(child, cloned);
});
});
}
});
$('body').removeClassWithStyles([
'float', 'position', 'top', 'right', 'bottom', 'left'
]);
body {
position: relative;
}
.left {
float: left;
}
.right-abs {
position: absolute;
top: 20px;
right: 100px;
}
.top-abs {
position: absolute;
top: 20px;
}
.center {
text-align: center;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="left">
<h1>Hello</h1>
</div>
<div class="right-abs top-abs center">
<h3>World</h3>
</div>
也在 Fiddle
说明:
我们正在将元素样式与默认浏览器样式进行比较,因此我们知道这些样式是否被特定类更改。
关于jquery - 如何通过Jquery判断类中是否存在样式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39220891/