Get element's custom css properties (-mystyle) using JavaScript

后端 未结 7 1797
南旧
南旧 2020-11-28 14:13

In an application where certain elements have custom CSS properties, is there any way to retrieve such a value via JavaScript?

e.g.

7条回答
  •  臣服心动
    2020-11-28 15:12

    Non-recognised CSS properties will be ignored when put within the style attribute, or in the style.cssText property.

    If you want to define a property at a specific element, I recommend data-attributes:
    HTML:

    JavaScript:

    //jQuery's method to retrieve value:
    $("#myDiv").data("custom-property");
    //jQuery, without parsing:
    $("#myDiv").attr("data-custom-property");
    
    // Modern browsers, native JS:
    document.getElementById("myDiv").dataset["custom-property"];
    // Older browsers, native JS:
    document.getElementById("myDiv").getAttribute("data-custom-property");
    

提交回复
热议问题