每30秒更换一次背景颜色(淡入淡出过渡)

Bil*_*f32 12 css background colors fade css-transitions

我希望有人告诉我,制作网页背景颜色(整个页面的背景颜色)的代码是什么,每30秒更改一次(淡入淡出过渡)到给定的颜色种类.这很简单吗?我猜css会让它变得更容易吗?

我在网上搜索过,我发现渐变不是我想要的.先感谢您.我搜索了codepen和jsfiffle的例子,但没有人有这么简单:/

示例:在浏览我的页面时,我希望背景颜色从蓝色变为绿色,然后变为橙色,再次变为蓝色,依此类推...... :)

cku*_*jer 29

使用CSS3动画,也可以在没有任何JavaScript的情况下完成此操作.

html,
body {
  height: 100%;
}

body {
  -webkit-animation: background 5s cubic-bezier(1,0,0,1) infinite;
  animation: background 5s cubic-bezier(1,0,0,1) infinite;  
}


@-webkit-keyframes background {
  0% { background-color: #f99; }
  33% { background-color: #9f9; }  
  67% { background-color: #99f; }
  100% { background-color: #f99; }
}

@keyframes background {
  0% { background-color: #f99; }
  33% { background-color: #9f9; }  
  67% { background-color: #99f; }
  100% { background-color: #f99; }
}
Run Code Online (Sandbox Code Playgroud)


Bog*_*tan 9

这样的小提琴

CSS:

body {
    background: blue; /* Initial background */
    transition: background .5s; /* .5s how long transitions shoould take */
}
Run Code Online (Sandbox Code Playgroud)

使用Javascript:

var colors = ['green', 'orange', 'blue']; // Define Your colors here, can be html name of color, hex, rgb or anything what You can use in CSS
var active = 0;
setInterval(function(){
    document.querySelector('body').style.background = colors[active];
    active++;
    if (active == colors.length) active = 0;
}, 30000);
Run Code Online (Sandbox Code Playgroud)


Mar*_*tus 5

这是一种 jQuery 方法,用于完成 Bogdan 的回答,它需要 3 个参数:(selector例如,“.container”或“div”)、colors(要在两者之间切换的颜色数组)和time(控制 bgd 颜色更改的频率)。我将它设置为 3 秒 ( 3000),这样您就可以更轻松地看到它的运行情况,但您可以将其增加到 30000(30 秒)。

jQuery(function ($) {
    function changeColor(selector, colors, time) {
        /* Params:
         * selector: string,
         * colors: array of color strings,
         * every: integer (in mili-seconds)
         */
        var curCol = 0,
            timer = setInterval(function () {
                if (curCol === colors.length) curCol = 0;
                $(selector).css("background-color", colors[curCol]);
                curCol++;
            }, time);
    }
    $(window).load(function () {
        changeColor(".container", ["green", "yellow", "blue", "red"], 3000);
    });
});
Run Code Online (Sandbox Code Playgroud)
.container {
    background-color: red;
    height:500px;
    -webkit-transition: background-color 0.5s ease-in-out;
    -moz-transition: background-color 0.5s ease-in-out;
    -o-transition: background-color 0.5s ease-in-out;
    -khtml-transition: background-color 0.5s ease-in-out;
    transition: background-color 0.5s ease-in-out;
}
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="container"></div>
Run Code Online (Sandbox Code Playgroud)