简体   繁体   中英

How can I prevent CSS from affecting certain element?

I am writing a GreaseMonkey script that sometimes creates a modal dialog – something like

<div id="dialog">
   Foo
</div>

. But what can I do if the site has something like

#dialog {
    display: none !important;
}

? Or maybe the owner of some site is paranoid and has something like

div {
    display: none !important;
}
div.trusted {
    display: block !important;
}

because he doesn't want people like me adding untrusted content to his page. How can I prevent those styles from hiding my dialog?

My script runs on all pages, so I can't adapt my code to each case.

Is there a way to sandbox my dialog?

Actually a very interessting problem, here is another approach:

adding an iframe and modifying it creates a seperate css space for you (your sandbox)

look at this jsfiddle example: http://jsfiddle.net/ZpC3R/2/

var ele = document.createElement("iframe");
ele.id = "dialog";
ele.src = 'javascript:false;';
ele.style.height = "100px";
ele.style.width = "300px";
ele.style.setProperty("display", "block", "important");
document.getElementById("dialog").onload = function() {
    var d = document.getElementById("dialog").contentWindow.document;
    // ... do your stuff within the iframe
};

this seems to work without problem in firefox.

now you only have to make sure that the iframe is untouched, you can do this they way i described in my 1. answer

just create the div like this:

var ele = document.createElement("div");
ele.style.setProperty("display", "block", "important");

that should overwrite all other styles afaik.

look here, it seems to work: http://jsfiddle.net/ZpC3R/

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