最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Change text colors every second - Stack Overflow

programmeradmin1浏览0评论

HTML Code

function changeColor() {
  var x = document.getElementById("li1");
  x.style.color = "blue";
  if (x.style.color == "blue") {
    x.style.color = "yellow";
  }
}
window.setInterval("changeColor", 1000);
<body>
  <div class="leftDiv">
    <div id="stepsId">
      <ol>
        <li id="li1"><b>Step 1</b></li>
        <li id="li2"><b>Step 2</b></li>
        <li id="li3"><b>Step 3</b></li>
      </ol>
    </div>
  </div>
</body>

HTML Code

function changeColor() {
  var x = document.getElementById("li1");
  x.style.color = "blue";
  if (x.style.color == "blue") {
    x.style.color = "yellow";
  }
}
window.setInterval("changeColor", 1000);
<body>
  <div class="leftDiv">
    <div id="stepsId">
      <ol>
        <li id="li1"><b>Step 1</b></li>
        <li id="li2"><b>Step 2</b></li>
        <li id="li3"><b>Step 3</b></li>
      </ol>
    </div>
  </div>
</body>

My main goal is to cycle through the colors from steps 1 to 3 with each step turning blue > yellow > blue > yellow every second in ascending order. I cannot figure out what am I doing wrong.

Share edited Apr 13, 2017 at 4:59 Shadow 9,4274 gold badges49 silver badges59 bronze badges asked Apr 13, 2017 at 4:00 user7644293user7644293 5
  • Is this correct? – Tushar Commented Apr 13, 2017 at 4:06
  • 1. add a closing bracket "}" to the changeColor function. 2. remove the quotes in windows.setinterval: window.setInterval(changeColor,1000); 3. make sure the javascript is loaded after the DOM has loaded. – alfredo Commented Apr 13, 2017 at 4:10
  • window.setInterval("changeColor", 1000); needs to not have quotes around the function name... – Shadow Commented Apr 13, 2017 at 4:12
  • "each step ... in ascending order" - Do you mean that when steps 1 and 3 are blue step 2 should be yellow, and vice versa? Or...? Your current code only tries to change the li1 element. – nnnnnn Commented Apr 13, 2017 at 4:14
  • by ascending order I meant, All steps appear Blue at first and upon running the code yellow starts cycling through steps 1,2,3. – user7644293 Commented Apr 13, 2017 at 4:36
Add a ment  | 

8 Answers 8

Reset to default 3

Your existing JS doesn't work because you left the closing } off your function, and because in the call to setInterval() the function name in the first argument should not be in quotes (that is, pass a function reference, not a string).

But also, your code only references the first element in the list, and you said you want to change "each step...in ascending order". So maybe you could do something like the following, using document.querySelectorAll("#stepsId li") to select all of the li elements, then loop over them to change their colours in sequence:

var colors = ["blue", "yellow"]
var currentColor = 0
var lis = document.querySelectorAll("#stepsId li")

function changeColor() {
  --currentColor
  if (currentColor < 0) currentColor = colors.length -1
  for (var i = 0; i < lis.length; i++) {
    lis[i].style.color = colors[(currentColor +i) % colors.length]
  }
}

setInterval(changeColor, 1000)
<div id="stepsId">
  <ol>
    <li id="li1"><b>Step 1</b></li>
    <li id="li2"><b>Step 2</b></li>
    <li id="li3"><b>Step 3</b></li>
  </ol>
</div>

Note that you can add any number of colours into the array and it will cycle through all of them:

var colors = ["blue", "yellow", "red", "green", "orange"]
var currentColor = 0
var lis = document.querySelectorAll("#stepsId li")
function changeColor() {
  --currentColor
  if (currentColor < 0) currentColor = colors.length -1
  for (var i = 0; i < lis.length; i++) {
    lis[i].style.color = colors[(currentColor +i) % colors.length]
  }
}
setInterval(changeColor, 1000)
<div id="stepsId">
  <ol><li id="li1"><b>Step 1</b></li><li id="li2"><b>Step 2</b></li><li id="li3"><b>Step 3</b></li></ol>
</div>

To achieve expected result, use below option

1.Initialize color outside function
2.toggle color using setInterval

Codepen URL for reference- http://codepen.io/nagasai/pen/NjWBxv

JS:

var x = document.getElementById("li1");
 x.style.color = "blue";

function changeColor(){
 x.style.color = x.style.color == "blue"?"yellow":"blue";
}

window.setInterval(changeColor,1000);

There are few syntax errors like missing close '}' and remove quotes for function as it is not a string

Here is working code

    <html>
    <head>
    <script type="text/javascript">

      var x = setInterval(function() {

        console.log('rrr');
       var x = document.getElementById("li1");
            x.style.color = "blue";
            if (x.style.color == "blue"){
            x.style.color = "yellow";
            }
        }, 1000);

    </script>
    </script>
    <body>   
     <div class="leftDiv">
          <div id = "stepsId" > 
            <ol>
              <li id="li1"><b>Step 1</b></li>
              <li id="li2"><b>Step 2</b></li>
              <li id="li3"><b>Step 3</b></li>
            </ol>
          </div>
        </div>
    </body>
    </html>

This works

<!DOCTYPE html>
    <html>
<head>
    <script>

        window.onload = function(){

        var x = document.getElementById("li1");
        x.style.color = "blue";

        function changeColor(){
            if (x.style.color == "blue"){
                x.style.color = "yellow";
            }
            else if (x.style.color == "yellow"){
                x.style.color = "blue";
            }
        };
        window.setInterval(changeColor,1000);



        };
    </script>
</head>
<body>
 <div class="leftDiv">
      <div id = "stepsId" > 
        <ol>
          <li id="li1"><b>Step 1</b></li>
          <li id="li2"><b>Step 2</b></li>
          <li id="li3"><b>Step 3</b></li>
        </ol>
      </div>
    </div>
</body>
</html>

You're only trying to change li1, rather than all of the li elements, which I assume is your intention. Try using document.querySelectorAll instead of document.getElementById and then iterating through the array, like so

function changeColor() {
  var x = document.querySelectorAll("#stepsId li");

    for (var i = 0; i < x.length; i++) {
        x[i].style.color = x[i].style.color === 'blue' ? 'yellow' : 'blue';
   }
}
window.setInterval(changeColor, 1000);

This answer assumes that you want them all changing to the same color at the same time.

Refer this code

<html>
<head>
<script type="text/javascript">
  var i = 1;
  var x = setInterval(function() {
   var x = document.getElementById("li1");
   console.log(x.style.color);
        if (x.style.color == "blue"){
          x.style.color = "yellow";
        } else if (x.style.color === "yellow"){
      x.style.color = "red";
    } else if (x.style.color === "red"){
      x.style.color = "blue";
    }

    }, 1000);

</script>
</script>
<body>   
 <div class="leftDiv">
      <div id = "stepsId" > 
        <ol>
          <li id="li1" style="color: blue;"><b>Step 1</b></li>
          <li id="li2"><b>Step 2</b></li>
          <li id="li3"><b>Step 3</b></li>
        </ol>
      </div>
    </div>
</body>
</html>

Two things to consider first:

  1. The JavaScript you posted is not syntactically valid because you fail to close your if statement curly brace (the "}").
  2. The code inside your function will quickly. The only color change that you will see on the page is the final color value when your function finishes.

You will need to keep track of which element is yellow at any particular point and set up your function to determine which element should be turned yellow next.

var li1 = document.getElementById("li1");
var li2 = document.getElementById("li2");
var li3 = document.getElementById("li3");
var yellow = li1;

function changeColor() {
  if(li1 == yellow) {
    yellow = li2;
  } else if(li2 == yellow) {
    yellow = li3;
  } else {
    yellow = li1;
  }

  li1.style.color = "blue";
  li2.style.color = "blue";
  li3.style.color = "blue";
  yellow.style.color = "yellow";
}

window.setInterval(changeColor, 1000);

This is how you can achieve a cycle! But be careful while selecting lis, beacuse I just used getElementsByTagName which will give you all the li element

var lis = document.getElementsByTagName("li");
var i = 0
var color ='blue'
function changeColor(){
  if(i==3){
    i=0
  } 
  lis[i].style.color = color;
  if (lis[i].style.color == "blue"){
    color = 'yellow'
  }
  else{
    color = 'blue'
  }
  i = i+1;
}
window.setInterval(changeColor,1000);
<html>
<body>   
 <div class="leftDiv">
      <div id = "stepsId" > 
        <ol>
          <li id="li1"><b>Step 1</b></li>
          <li id="li2"><b>Step 2</b></li>
          <li id="li3"><b>Step 3</b></li>
        </ol>
      </div>
    </div>
</body>
</html>

发布评论

评论列表(0)

  1. 暂无评论