How can I “reset” styles for a given HTML element?

2020-05-26 10:09发布

I am working on an embeddable javascript which inserts HTML elements onto unknown pages. I have no control of the stylesheets of the pages I'll be inserting HTML into. The problem is that the HTML I insert will mistakenly stylized by the page, and I want to prevent that.

What's the least verbose and/or resource intensive to go about ensuring the elements I insert are exactly as I'd like them to be? Is there an easy way to clear all styling for a given HTML element and children? In firebug, for instance, you can remove all styling. I feel like there must, and the very least should, be a native way to exempt certain HTML elements from stylesheet rules?

Example:

var myHTML = $("<div>my html in here</div>");
myHTML.resetAllStyles();   //<--- what would this function do?
myHTML.appendTo("body");

I really want to avoid explicitly stating the attributes I want for each element I insert...

PS: I have a lot of experience with JS and CSS, so you can assume that I'll understand pretty much anything you're going to tell me.

2条回答
Viruses.
2楼-- · 2020-05-26 10:45

You cannot prevent an element inheriting CSS styles from parent nodes. All you can do is overwriting all styles that has been inherited.

查看更多
叛逆
3楼-- · 2020-05-26 10:47

I'm going to throw this out there as a possibility. How about custom tags for your bookmarklet? Requires a little more tinkering with a custom xml namespace because of IE, but may be workable for you.

jQuery doesn't seem to mind either.

http://jsfiddle.net/uvfAf/1/

jQuery:

$('#tester').animate({opacity: .3},1000);

HTML:

   // Not the main HTML tags. These are embedded in the body as the root
   //   of the bookmarklet. Scary? Perhaps.
<html xmlns:customtag>
    <style> 
        @media all {  
          customtag\:someElement { 
            width:100px; 
            height: 100px; 
            background: blue; 
            display: block; 
          } 
          customtag\:someOtherElement { 
            width: 50px; 
            height: 50px; 
            background: red; 
            display: block; 
          }
        }
    </style>
    <customtag:someElement id='tester'>test</customtag:someElement>
    <customtag:someOtherElement>test</customtag:someOtherElement>
</html>​

I used this page to figure out how to do custom tags in IE:

http://happyworm.com/blog/tag/custom-tags/

EDIT:

Looks like IE wants the xmlns to be defined in HTML tags, so I changed the container to <html>. Not sure of the ramifications overall, but seems to work.

I updated the example and the jsFiddle.

查看更多
登录 后发表回答