使用javascript改变CSS类属性? [英] Alter CSS class attributes with javascript?

查看:121
本文介绍了使用javascript改变CSS类属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个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>

此代码根据这个问题,这是非常类似于你问的。每当你需要改变所有.Foo元素的位置,你可以调用changeFoo(newLeftValue,newTopValue); - 第一次创建< style> 元素并将其添加到< head 文档。后续调用只会清空已添加的< style> 元素,并添加新规则。

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆