JavaScript foreach通过一组十六进制值循环,使用setTimeout循环通过背景颜色 [英] JavaScript foreach loop through an array of hex values, using setTimeout to loop through background colors

查看:128
本文介绍了JavaScript foreach通过一组十六进制值循环,使用setTimeout循环通过背景颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在试图用最简洁的方式来使用JavaScript来改变背景颜色。 (试图获得forEach和更高阶的函数只是为了好玩)无论如何,这将运行在页面加载,我想我非常接近:

 function background(){
var colorArray = [#14183b,#002e2e,#0d2d40,#173052,#194759,#296b73 ];
function change(newcolor){
document.body.style.backgroundColor = newcolor; (颜色){
setTimeout(change(color),1000);
});

colorArray.forEach





$ b

问题是背景颜色只显示数组中的最后一个元素。我也不知道如何在完成后再次启动forEach循环。感谢您的帮助!

解决方案



var colorArray = [#14183b,#002e2e,#0d2d40,#173052,#194759,#296b73];

var count = 0;

  function change(){
document.body.style.backgroundColor = colorArray [count];
count ++;
if(count == colorArray.length){
count = 0;


$ b setInterval(function(){
change();
},1000);


I've been trying to come up with the most concise way that I can possibly change background colors using JavaScript. (Trying to get the hang of forEach and higher order functions just for fun.) Anyway, this will run on page load, and I think I'm pretty close:

function background(){
    var colorArray = ["#14183b", "#002e2e", "#0d2d40", "#173052", "#194759", "#296b73"];
    function change(newcolor){
        document.body.style.backgroundColor=newcolor;
    }
    colorArray.forEach(function(color){
        setTimeout(change(color), 1000);
    });
}

The problem is that the background color is only showing the last element in the array. I also am not sure how to start the forEach loop over again when it is has finished. Thanks for any help!

解决方案

Like this ... Also can ...

var colorArray = ["#14183b", "#002e2e", "#0d2d40", "#173052", "#194759", "#296b73"];

var count = 0;

    function change() {
        document.body.style.backgroundColor = colorArray[count];
        count++;
        if(count == colorArray.length) {
            count = 0;
        }
    }

    setInterval(function(){
        change();
    }, 1000);

这篇关于JavaScript foreach通过一组十六进制值循环,使用setTimeout循环通过背景颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆