简体   繁体   中英

Can one detect if an element's style is just the browser default vs. is set by a stylesheet or inline styles?

My javascript is included in X's site, but I don't have any other control over her site or where she includes it. If she's styled #element , I want to leave it alone, but if she hasn't, I've got a stylesheet I'll inject in <head> . Is there any way to detect whether or not she's styled it?

Checking it's height is 0 or 1 fails because it's got some content in it and the browser makes default decisions.

Any way for javascript/jquery/other framework to tell the CSS specificity of a style would answer this and be incredible.

A straightforward but imperfect way of knowing if there was an intent to style an element would be to check if the style attribute of the element has a value or if the class attribute of the element has been set.

http://jsfiddle.net/YbSpc/

HTML

<div id="test_unstyled"></div>
<div id="test_styled" style="background-color: red;" class="something"></div>

JS

var unstyled = document.getElementById('test_unstyled'),
    styled = document.getElementById('test_styled');

console.log('test_unstyled is styled?', !!(unstyled.getAttribute('style') || unstyled.className));
console.log('test_styled is styled?', !!(styled.getAttribute('style') || styled.className));

However, this solution will not detect any styles applied through CSS selectors. If you want to take these in account, you will probably have to find out all the default styles applied by browsers and check against that, but this will get very hard to maintain and I don't recommend trying to implement this approach unless you are willing to develop and maintain a library for that sole purpose.

If you are publishing a plugin that others might use, it would probably be easier to implement an API that would allow the plugin's client to decided wether they want the plugin styles to be applied or not.

You could also always include your stylesheet and users will be able to override the styles by loading their custom stylesheet.

For inline style, it's quite easy: you can just access to element.style object and check the property you want to – or use element.hasAttribute('style') to check if the attribute is defined in the HTML.

For CSS rules applied by stylesheet, I would suggest to you to take a look at " Is it possible to check if certain CSS properties are defined inside the style tag with Javascript? " that it's quite similar from what are you asking.

Using the approach described there, is also quite easy filtered the rules that have only the #element selector in, if you want to filter out any generic rule (like tag ones).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM