简体   繁体   English

如何使用JS动态更改CSS

[英]How to dynamically change CSS using JS

I am working on complicated animation, I am trying to add effects by adding another class based on the val I am getting. 我正在制作复杂的动画,我正在尝试通过基于所获取的val添加另一个类来添加效果。

I have different css classes, and I wanna know how to dynamically add them this way. 我有不同的CSS类,并且我想知道如何以这种方式动态添加它们。

.. Class="box bottom right" 

when I add new class (eg: red). 当我添加新类时(例如:红色)。 It should be in my code this way: 应该在我的代码中是这样的:

.. Class="box bottom right red" 

I am trying to change the css based on value I am calculating. 我正在尝试根据要计算的值更改css。

var els=2;

  function changeColor(els) {
    if (els>0) {
            $("box bottom right").addClass("red");
    } else{
            $("box bottom right").addClass("green");
    };

  } 

Here is code: http://jsfiddle.net/BB6ED/1/ 这是代码: http : //jsfiddle.net/BB6ED/1/

You need to use . 您需要使用. to target elements by class as well as calling your function on page load: 按类定位元素以及在页面加载时调用函数:

var els=2;

  function changeColor(els) {
    if (els>0) {
            $(".box.bottom.right").addClass("red");
    } else{
            $(".box.bottom.right").addClass("green");
    };

  }

changeColor(els);

Updated Fiddle 更新小提琴

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM