JavaScript--利用setInterval或setTimeout实现背景颜色轮播

来源:互联网 发布:java web get post 编辑:程序博客网 时间:2024/06/10 22:15

Window属性---暂停和定时器

暂停

var timeoutObj = setTimeout("执行程序",毫秒)

  1. setTimeout(引用,1000)
  2. setTimeout("执行程序",1000)

clearTimeout(timeoutObj)


定时器

var intervalObj = setInterval(("执行程序",毫秒)

  1. setInterval(引用,1000)
  2. setInterval("执行程序",1000)

clearInterval(intervalObj)


例题:

利用setTimeout实现背景颜色轮播

完整代码如下:

<!DOCTYPE html><html><head lang="en">    <meta charset="UTF-8">    <title></title>    <style type="text/css">        div {            width: 200px;            height: 200px;            border: 1px solid black;            background-color: red;        }    </style></head><body>    <div></div></body><script type="text/javascript">    var divEle = document.getElementsByTagName("div")[0];    func1();    function func1() {        divEle.style.backgroundColor = "red";        setTimeout(func2, 1000);    }    function func2() {        divEle.style.backgroundColor = "yellow";        setTimeout(func3, 1000);    }    function func3() {        divEle.style.backgroundColor = "blue";        setTimeout(func1, 1000);    }</script></html>

利用setInterval实现背景颜色轮播

完整代码如下:

<!DOCTYPE html><html><head lang="en">    <meta charset="UTF-8">    <title></title>    <style type="text/css">        div {            width: 200px;            height: 200px;            border: 1px solid black;            background-color: red;        }    </style></head><body>    <div></div></body><script type="text/javascript">    var divEle = document.getElementsByTagName("div")[0];    var colors = ["red", "yellow", "blue"];    var count = 0;    setInterval(func, 1000);    function func() {        divEle.style.backgroundColor = colors[count++];        if (count === 3) count = 0;    }</script></html>





0 0
原创粉丝点击