简体   繁体   English

我想使用JavaScript切换CSS属性

[英]I want to toggle CSS property using javascript

<div class="content">
          <?php
            for ($i=0; $i < 5; $i++) {
              echo '<div class="foo">
              </div>';
            }
          ?>
          <script>
            var foo= document.getElementsByClassName('foo');
            for (var i = 0; i < foo.length; i++) {
              foo[i].addEventListener("click", function(){
                this.style.backgroundColor = "lightgreen";
                });
            }
          </script>

I have created one div class called "content" and inside that content div there are five divs generated using php for loop. 我创建了一个称为“ content”的div类,在该内容div中,使用php for loop生成了五个div。 I want to change the divs "foo" background color to light green which is achieved already, but my concern is how to change the background color property again to white? 我想将divs“ foo”背景颜色更改为已经实现的浅绿色,但是我担心的是如何再次将背景颜色属性更改为白色?

Extending the Lahiru TM approach 扩展Lahiru TM方法

Try using this, so that it will toggle the color on click 尝试使用它,这样它将在点击时切换颜色

<div class="content">
     <?php
       for ($i=0; $i < 5; $i++) {
          echo '<div class="foo">test
           </div>';
       }
     ?>
</div>
<script>
var foo= document.getElementsByClassName('foo');
for (var i = 0; i < foo.length; i++) {
    foo[i].addEventListener("click", function(e){
        if (this.style.backgroundColor == 'lightgreen') {
            this.style.backgroundColor = "white";
        } else {
            this.style.backgroundColor = "lightgreen";
        }
    });
}
</script>

You can try below approach for that, 您可以尝试以下方法,

<script>
var foo= document.getElementsByClassName('foo');
for (var i = 0; i < foo.length; i++) {
    foo[i].addEventListener("click", function(e){
        if (e.style.backgroundColor) {
            e.style.backgroundColor = "null";
        } else {
            e.style.backgroundColor = "lightgreen";
        }
    });
}
</script>

It is advisable to use the CSS class then of a class property. 建议先使用CSS类,然后再使用class属性。

You can do something like this 你可以做这样的事情

    <div class="content">
         <?php
           for ($i=0; $i < 5; $i++) {
              echo '<div id="i" class="preToggle" (click)="divClicked($event , i)">test
               </div>';
           }
         ?>
    </div>
    <script>
    divClicked(event , i){
        var foo= document.getElementById(i);
        foo.className = foo.className.replace("preToggle", "postToggle");
}
    </script>

define CSS for preToggle and postToggle. 为preToggle和postToggle定义CSS。

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

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