Can jQuery get all CSS styles associated with an element?

前端 未结 5 1152
谎友^
谎友^ 2020-11-21 06:31

Is there a way in jQuery to get all CSS from an existing element and apply it to another without listing them all?

I know it would work if they were a style attribut

5条回答
  •  清酒与你
    2020-11-21 06:55

    I had tried many different solutions. This was the only one that worked for me in that it was able to pick up on styles applied at class level and at style as directly attributed on the element. So a font set at css file level and one as a style attribute; it returned the correct font.

    It is simple! (Sorry, can't find where I originally found it)

    //-- html object
    var element = htmlObject; //e.g document.getElementById
    //-- or jquery object
    var element = htmlObject[0]; //e.g $(selector)
    
    var stylearray = document.defaultView.getComputedStyle(element, null);
    var font = stylearray["font-family"]
    

    Alternatively you can list all the style by cycling through the array

    for (var key in stylearray) {
    console.log(key + ': ' + stylearray[key];
    }
    

提交回复
热议问题