问题描述:

I need a JavaScript/jQuery way of "hijacking" a CSS definition that is not based on a class or ID.

An example CSS:

input {

border: 1px solid red;

}

If I then have a document with, say, a <span> element in it, I'd want to add this element to this definition.

So I'd do $(this).magicAwesome(); and the red border defined in the input CSS definition would also be applied to this non-input element.

Is there a way to achieve this effect? I don't care if it's hackish. :)

Thanks a bunch in advance!

网友答案:

You can either read the computed style for a selected element, then copy that, or read the CSS declaration from the stylesheet itself. Reading stylesheets is a bit of a pain because of IE vs. Standards.

See: Dynamically add referenced stylesheet to inline styles

http://www.javascriptkit.com/domref/stylesheet.shtml

https://developer.mozilla.org/en/DOM/document.styleSheets

网友答案:

You can copy all styles from a temporary 'donor' element and set them to your span: http://jsfiddle.net/UxFUr/

It does everything you wanted:

  • it changes the styles of the span to the css styles of "input"
  • it's named magicAwesome!
  • bonus: it's hackish...

the code:

$.fn.magicAwesome=function(){
    var donor=$('<input />').appendTo('body');
    $(this).css(donor.getStyleObject());
    donor.remove();
}

And then set a click event or something to trigger the function $(this).magicAwesome();

I used the getStyleObject function from CopyCss

网友答案:

If you know what you want duplicate from stylesheet, you can try this: http://jsfiddle.net/YHYQe/

相关阅读:
Top