Cloning a css style from a style sheet using jquery/greasemonkey
I am writing a Greasemonkey script using jquery, and I want to add information from multiple pages, but the o开发者_JAVA百科bject i want to load is a div with an Id, is there any way I can retrieve the style information, so that I can apply it to the added sections?
Take a look at getComputedStyle()
This is untested, but the code would be something like this:
var someOtherElement = document.getElementById('blah');
var style = window.getComputedStyle(document.getElementById('myId'), '');
for (var i in style) {
if (style.hasOwnProperty(i)) {
someOtherElement.style[i] = style[i];
}
}
This will only work (well, this probably doesn't work at all, but the basic idea of it will only work) with Firefox, but since you said you're using greasemonkey, I assume that's not a concern for you.
I think my brain isn't working properly this morning - but in any case, here's something which works, but in a dodgy way. Loop through the styles of the element you are copying them to.
var s = window.getComputedStyle(document.getElementById('myElement'), null);
var someOtherElement = document.getElementById('someOther');
for (var i in someOtherElement.style) {
try {
someOtherElement.style[i] = s[i];
} catch (e) { }
}
Like I said, my brain is not working and the above is dodgy. The style
object has properties length
and parentRule
which are read-only which makes it die, hence the try/catch.
精彩评论