使用javascript改变CSS类属性? [英] Alter CSS class attributes with javascript?
问题描述
我有一个CSS类定义,调用它:
I have a CSS class defined, call it:
<style type="text/css">
.Foo { position: fixed; left: 50px; top: 50px; }
</style>
我在屏幕上放置一个元素。在我的网页的执行,我创建和删除许多元素,并给他们 Foo
。当我调整浏览器大小时,我想更改 Foo上的
类,因此 all 左
和顶部
Foo
元素的位置会因计算结果而改变。
where I position an element on the screen absolutely. Throughout my web page's execution, I create and delete many elements and give them class Foo
. When I resize the browser, I want to change the left
and top
values on the Foo
class so the position of all Foo
elements is changed as a result of a calculation.
我不想简单的更改样式表,我想计算一个值,并使所有当前和未来的 Foo
元素有新的计算左
和顶部
值。
I don't want to simply change stylesheets, I want to calculate a value and make all current and future Foo
elements have that new calculated left
and top
value.
例子,但代码相当复杂。
http:// www。 shawnolson.net/a/503/altering-css-class-attributes-with-javascript.html
This site has an example, but the code's quite complex. http://www.shawnolson.net/a/503/altering-css-class-attributes-with-javascript.html
基本上是以编程方式有一个好的,干净的方式alter Foo
定义为
Is there a good, clean way to basically programmatically alter what Foo
is defined as?
谢谢!
推荐答案
我认为这是你想要的:
<script>
var style;
function changeFoo(left, top) {
if(typeof style == 'undefined') {
var append = true;
style = document.createElement('style');
} else {
while (style.hasChildNodes()) {
style.removeChild(style.firstChild);
}
}
var head = document.getElementsByTagName('head')[0];
var rules = document.createTextNode(
'.Foo { left: ' + left + 'px; top: ' + top + 'px; }'
);
style.type = 'text/css';
if(style.styleSheet) {
style.styleSheet.cssText = rules.nodeValue;
} else {
style.appendChild(rules);
}
if(append === true) head.appendChild(style);
}
</script>
This code was modified from an answer provided in this question which is very similar to what you asked. Whenever you need to change the position of all .Foo elements, you can just call changeFoo(newLeftValue, newTopValue); - the first time around it will create the <style>
element and add it to the <head
> of the document. Subsequent calls will just empty the <style>
element that was already added and add the new rule.
这篇关于使用javascript改变CSS类属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!