JQuery how to set class css data to a div but without setting class name or with other class name
I need to copy a class data to a div, but without setting class name or with other class name.
for instance:
$('#blabla').addClass('xxx');
开发者_如何学编程And then remove the class name but leaving the style data. The thing is that I need to set the style information but I can't set the class name because It gets conflicted with some other code.
Use getComputedStyle
to get all styles applied to the object. Note that this may be a really big list.
var sourceDiv = $('#source');
var targetDiv = $('#target');
// IE 6,7,8 doesn't support this. Google how to make this cross-browser
var styles = window.getComputedStyle(sourceDiv.get(0), null);
var property, value;
for(var i = 0; i < styles.length; i++) {
name = styles[i];
value = sourceDiv.css(name);
targetDiv.css(name, value);
}
This shows me 207 properties for each element on Chrome. If you are applying this to a lot of elements, it may slow things down. A faster approach in that case would be to tap directly into the CSS rules and styles declared by jQuery UI, and manipulate only the styles declared in the css file, and not the entire computed styles.
Depending on what styles you're trying to apply, it may work to do the following:
- addClass()
- Get the CSS properties from your element and apply them using the css() method
- removeClass()
Code:
var blabla = $('#blabla');
blabla.addClass('xxx');
blabla.css({
fontWeight: blabla.css('fontWeight'),
display: blabla.css('display'),
float: blabla.css('float'),
});
blabla.removeClass('xxx');
You could loop through all computed styles for that element and apply them in a style attribute, then remove the class name. Or perhaps parse the CSS rules and apply the styles from .xxx that way.
You can loop through all CSS properties like this:
var elem = $('#blabla')[0],list = {},props;
if (document.defaultView && document.defaultView.getComputedStyle) {
props = document.defaultView.getComputedStyle(elem, "");
$.each(props, function(i, prop) {
list[prop] = props.getPropertyValue(prop);
});
} else if (elem.currentStyle) { // IE
props = elem.currentStyle;
$.each(props, function(prop, val) {
list[prop] = val;
});
}
console.log(list) // the entire computed style object
If you do this you will also get all the inherited and computed styles, even from the browser CSS.
精彩评论