Javascript: Create element that does not inherit css?

时间:2016-04-15 11:11:17

标签: javascript html

I'm making a simple greasemonkey script for school that adds an ugly yellow box with some links to all websites. Currently I simply do this:

var guesses_div = document.createElement("div");
guesses_div.style.position = "fixed";
guesses_div.style.right = "0";
guesses_div.style.bottom = "0";
guesses_div.style.backgroundColor = "rgb(255, 255, 0)"
// here I add some links to the "guesses_div"

This code works fine. However, it inherits the style from the web page it's on. Is there a way to prevent this? Other than overriding all the style elements one by one?

Thanks!

4 个答案:

答案 0 :(得分:2)

Short answer: No. There is no way to prevent the inherited css.

Long answer: Yes. You should manually override the inherited css rules.

答案 1 :(得分:1)

Not sure if it's the nicest way ever to do things, but in html5 you can use close to everything as tag name - so to not let your div inherit the sites css rules for a div, simply don't create a div, but myDiv for example

var guesses_div = document.createElement("myDiv");
guesses_div.style.position = "fixed";
guesses_div.style.right = "0";
guesses_div.style.bottom = "0";
guesses_div.style.backgroundColor = "rgb(255, 255, 0)"

FIDDLE

答案 2 :(得分:0)

如何插入div代替iframe? {{1}}不会从其父级继承样式。

如果有疑问如何操作,请参阅this问题。

答案 3 :(得分:0)

您可以查看all属性,并执行以下操作:

var guesses_div = document.createElement("div");
guesses_div.style.all = "unset";
guesses_div.style.position = "fixed";
guesses_div.style.right = "0";
guesses_div.style.bottom = "0";
guesses_div.style.backgroundColor = "rgb(255, 255, 0)";

不幸的是,这在IE或Safari中不起作用,但是当您使用Greasemonkey(我认为仅适用于Firefox)时,您应该没问题。

相关问题