开发者社区> 问答> 正文

我有一个问题,想要隔一段时间让div换颜色?这该怎么写比较好:报错

我有一个问题,想要隔一段时间让div换颜色?假设有3个div然后按照顺序div1过几秒钟,换到显示div2,再换到div3,颜色分别不同~请问有js高手~知道怎么做吗?

展开
收起
kun坤 2020-06-09 23:27:13 401 0
1 条回答
写回答
取消 提交回答
  • 随手写的,不知道你说的随机颜色是不是这样 你试试

    <html>
    <head>
    	<style type="text/css">
    	div{ border: 1px solid #999; width: 100px; height: 50px; margin-top: 10px; }
    	</style>
    	
    	<script >
    		window.onload = function(){
    			var div = document.getElementsByTagName('div');
    			var i = 0;
    			var bgColor = ['#ff0000', '#00ff00', '#0000ff'];
    			setInterval(function(){
    				var random = Math.ceil(Math.random()*10)%(bgColor.length);
    				for( var e = 0; e < div.length; e++){
    					div[e].style.backgroundColor = '#ffffff';
    				}
    				div[i].style.backgroundColor = bgColor[random];
    				i++;
    				if( i >= 3 ) i = 0;
    			}, 1000);
    		};
    	</script>
    </head>
    <body>
    	<div ></div>
    	<div ></div>
    	<div ></div>
    </body>
    </html>



    ######噢~原来是这样写~感谢你!可以用~######

    改了下楼上的

    <html>
    <head>
        <style type="text/css">
        div{ border: 1px solid #999; width: 100px; height: 50px; margin-top: 10px; }
        </style>
         
        <script >
    	    function randomColor() {
    	    	var str = "0123456789abcdef"; 
    			var t = "#"; 
    			for(j=0;j<6;j++){
    				t = t+ str.charAt(Math.random()*str.length);
    			}
    	    	return t;
    	    }
            window.onload = function(){
                var div = document.getElementsByTagName('div');
                var i = 0;
                setInterval(function(){
                    for( var e = 0; e < div.length; e++){
                        div[e].style.backgroundColor = '#ffffff';
                    }
                    div[i].style.backgroundColor = randomColor();
                    i++;
                    if( i >= 3 ) i = 0;
                }, 1000);
            };
            
        </script>
    </head>
    <body>
        <div ></div>
        <div ></div>
        <div ></div>
    </body>
    </html>



    ######setInterval 尽量少用, 它返回一个对象, ######var index = 1; setInterval(function(){ var d = document.getElementById("div" + index); d.style.backgroundColor = getRandomColor(); index++; if (index > 3) { index = 1; } }, 1000); function getRandomColor() { return …; }
    2020-06-09 23:27:19
    赞同 展开评论 打赏
问答分类:
问答地址:
问答排行榜
最热
最新

相关电子书

更多
低代码开发师(初级)实战教程 立即下载
冬季实战营第三期:MySQL数据库进阶实战 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载