Retrieving CSS Values from External Stylesheets with Javascript/jQuery
In web development, it may be necessary to access CSS values from an external stylesheet without having the corresponding HTML element physically present on the page. This scenario often arises when generating content dynamically.
The commonly used jQuery method $('element').css('property') relies on the element being rendered in the page. However, to determine the CSS property value before the element is created, an alternative approach is required.
Using a Surrogate Element
One solution is to create a temporary, hidden surrogate element and read its computed style. jQuery's $("
").hide().appendTo("body") creates a hidden paragraph element in the page body. You can then invoke $p.css("color") to retrieve the CSS color property value.Example Code
// Scoping function to avoid creating a global (function() { var $p = $("<p></p>").hide().appendTo("body"); console.log($p.css("color")); $p.remove(); })();
Note: In this example, the external CSS file must define the "p" element with the desired style properties.
The above is the detailed content of How to Retrieve CSS Values from External Stylesheets Without Elements in Javascript/jQuery?. For more information, please follow other related articles on the PHP Chinese website!