我有一个简单的输入字段如下:
<input type="text" name="search_location" id="search_location" placeholder="Any Location" autocomplete="off">
使用jQuery,我试图让所有样式与它相关联。这个代码看起来像这样(从stackoverflow thread获得):
// Get all styles associated with element
var style = css(jQuery("#elementToGetAllCSS"));
function css(a) {
var sheets = document.styleSheets, o = {};
for (var i in sheets) {
var rules = sheets[i].rules || sheets[i].cssRules;
for (var r in rules) {
if (a.is(rules[r].selectorText)) {
o = $.extend(o, css2json(rules[r].style), css2json(a.attr('style')));
}
}
}
return o;
}
function css2json(css) {
var s = {};
if (!css) return s;
if (css instanceof CSSStyleDeclaration) {
for (var i in css) {
if ((css[i]).toLowerCase) {
s[(css[i]).toLowerCase()] = (css[css[i]]);
}
}
} else if (typeof css == "string") {
css = css.split("; ");
for (var i in css) {
var l = css[i].split(": ");
s[l[0].toLowerCase()] = (l[1]);
}
}
return s;
}
// Apply styles to target element
var style = css(jQuery("#elementToGetAllCSS"));
jQuery("#search_location").css(style);
一切都很好,除非涉及CSS伪选择器,例如:before和:之后我得到一个“无法识别的表达式”控制台错误。
有什么想法吗?
编辑 - 我的解决方案
下面的答案是有效的,尽管我有点担心未来的答案如何。考虑到这一点,有一种似乎工作正常的替代方案:
$.fn.getStyleObject = function(){
var dom = this.get(0);
var style;
var returns = {};
if(window.getComputedStyle){
var camelize = function(a,b){
return b.toUpperCase();
};
style = window.getComputedStyle(dom, null);
for(var i = 0, l = style.length; i < l; i++){
var prop = style[i];
var camel = prop.replace(/\-([a-z])/g, camelize);
var val = style.getPropertyValue(prop);
returns[camel] = val;
};
return returns;
};
if(style = dom.currentStyle){
for(var prop in style){
returns[prop] = style[prop];
};
return returns;
};
return this.css();
}
var styles = $('elementToGetAllCSS').getStyleObject();
this.css('search_location);
答案 0 :(得分:2)
您可以通过检查选择器是否包含::
for (var r in rules) {
if (typeof rules[r] == 'object' &&
'selectorText' in rules[r] &&
rules[r].selectorText.indexOf('::') == -1 &&
rules[r].selectorText.indexOf(':hover') == -1
) {
if (a.is(rules[r].selectorText)) {
o = $.extend(o, css2json(rules[r].style), css2json(a.attr('style')));
}
}
}