JavasScript不定式背景随功能而变化

时间:2017-05-08 17:18:34

标签: javascript html css

我很好奇是否有办法在用户停留在页面上时重复一项功能。我希望函数f1()重复更改div #gallery的颜色。它可能是一个不定式的循环或其他什么,请帮助我。



function f1() {
  setTimeout(
    function() {
      document.getElementById("gallery").style.backgroundColor = "blue";
    }, 3000);
  setTimeout(
    function() {
      document.getElementById("gallery").style.backgroundColor = "red";
    }, 6000); 
}

#gallery {
  width: 500px;
  height: 300px;
  background-color: red;
}

<body onload="f1()">
  <div id="gallery">
			
  </div>
</body>
&#13;
&#13;
&#13;

3 个答案:

答案 0 :(得分:2)

之前使用setInterval的方法真的很棒,但我个人希望对发生的事情有更多的控制,所以我会使用类似的东西进行重复:

fiddle

肉和骨头&#39;是这样的循环:

const target = document.getElementById('target');
const colors = ["red", "blue", "purple", "black", "gray", "aliceblue"];
const randomColor = () => {
    const randomInt = Math.floor(Math.random() * colors.length + 1);
    return colors[randomInt];
}
const userStillOnPage = true;

function f1(newInterval, continueWith) {
    target.style.background = randomColor();

    if (userStillOnPage) {
        setTimeout(continueWith || f1, newInterval || 1000);
    }
}


f1();

这种方法可以轻松地执行各种操作,例如通过更改间隔或甚至注入不同的延续函数来使循环更快。它非常强大,很容易被抽象为非常通用的东西!

答案 1 :(得分:1)

您可以使用 setInterval

无限循环您的javascript
<html>
<head>
<style>
#gallery {
  width: 500px;
  height: 300px;
  background-color: red;
}
</style>
</head>
<body onload="f1()">
  <div id="gallery">

  </div>
</body>
<script type="text/javascript"> 
function f1(){
  setInterval(oneSecondFunction, 9000);
};
function oneSecondFunction() {
  setTimeout(
    function() {
      document.getElementById("gallery").style.backgroundColor = "blue";
    }, 3000);
  setTimeout(
    function() {
      document.getElementById("gallery").style.backgroundColor = "red";
    }, 6000); 
}
</script>
</html>

答案 2 :(得分:1)

document.addEventListener('DOMContentLoaded', init);

function init() {
  var target = document.getElementById('gallery');
  setInterval(function() {
    target.style.backgroundColor = getRandomColor();
  }, 1000) 

  // From http://stackoverflow.com/questions/1484506/random-color-generator-in-javascript
  function getRandomColor() {
    var letters = '0123456789ABCDEF';
    var color = '#';
    for (var i = 0; i < 6; i++ ) {
        color += letters[Math.floor(Math.random() * 16)];
    }
    return color;
  }
}