最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - make HTML background always changing - Stack Overflow

programmeradmin1浏览0评论

What do I mean by 'Always changing'? Well, for example, the Windows 8 installing screen, you see a text at the middle that says:'You can get new apps from the store', and the background are changing from red to orange to yellow to green to cyan to blue to purple then to red. I mean, how do I do that to my HTML background with JavaScript?

What do I mean by 'Always changing'? Well, for example, the Windows 8 installing screen, you see a text at the middle that says:'You can get new apps from the store', and the background are changing from red to orange to yellow to green to cyan to blue to purple then to red. I mean, how do I do that to my HTML background with JavaScript?

Share Improve this question asked Sep 26, 2015 at 4:01 David XuDavid Xu 1791 gold badge3 silver badges14 bronze badges 1
  • 1 What have you tried? You can use "window.setInterval" to create a timer that calls your javascript function repeatedly. – David Commented Sep 26, 2015 at 4:03
Add a ment  | 

6 Answers 6

Reset to default 4

The most simplest, effective and shortest amount of code is to do this using some CSS and JS

CSS:

#myDiv {
    transition: background-color 2s;
}

Then you can set some colors in an array and call them when you need, or ever so often, or use the below function to generate random colors.

JS:

function randomColor() {
    return '#'+ ('000000' + (Math.random()*0xFFFFFF<<0).toString(16)).slice(-6)
}

Below is a working implementation that changes the color every 2 seconds.

function randomColor() {
    return '#'+ ('000000' + (Math.random()*0xFFFFFF<<0).toString(16)).slice(-6)
}

function setColor(){
    document.getElementById('myDiv').style.backgroundColor = randomColor();
    setTimeout(setColor, 2000);
}

setColor();
#myDiv {
    height: 150px;
    transition: background-color 2s;
}
<div id="myDiv"></div>

If you want to have changing colors, here is a script I wrote to produce a sky effect using CSS transitions.

It does create a new div over the targeted element and apply to both a radial-gradient. Then the upper one's opacity is changed to 0, revealing the background one, while the foreground-one changed value. It does produce a smooth transition effect.

You can pass restriction colors in the form of an array, a speed variable in the form of an Number, and the id of a target element.
You can also omit all those parameters.

I wrote it a long time ago, and it probably needs a lot of improvements, but I hope you can twirk it and make it useful for you :

function Sky() {
  var sky = {};

  function rand(x) {
    if (!x) x = 1;
    return Math.round(Math.random() * x);
  }

  var isArray = function(arr) {
    if (isArray in Array) return Array.isArray(arr);
    else return arr instanceof Array;
  }

  var Chuck = function(arr) {
    var total = 0;
    arr.forEach(function(e) {
      total += e
    })
    return (total / arr.length == 0 || total / arr.length == 255);
  }

  function nightDay() {
    var RGB = sky.RGB;
    var shouldChange = Chuck(RGB);
    if (shouldChange) sky.toNight = !sky.toNight;
    for (var i = 0; i < RGB.length; i++) {
      RGB[i] += (sky.toNight) ? 10 : -10;
      if (RGB[i] < 0) {
        RGB[i] = 0;
      }
      if (RGB[i] > 255) {
        RGB[i] = 255;
      }
    }

    return "radial-gradient( " +
      "rgba(" + (rand(RGB[0]) + RGB[1]) + " ," + (rand(RGB[2]) + RGB[3]) + " ," + rand(RGB[4] + RGB[5]) + ", 0.9) " + rand(25) + "%, " +
      "rgba(" + (rand(RGB[6]) + RGB[7]) + " ," + (rand(RGB[8]) + RGB[9]) + " ," + (rand(RGB[10]) + RGB[11]) + ", 0.9) " + (rand(25) + 500) + "%) " +
      "rgba(0, 0, 0, 0) repeat scroll " + rand(50) + "px " + rand(50) + "px / cover";
  }


  function changeOp(e) {
    var val = nightDay();
    var op = +sky.over.style.opacity;
    if (op > 0) {
      // First div is opaque
      if (!sky.isWebkit) {
        sky.el.style.background = val;
        if (!sky.el.style.background)
          sky.isWebkit = true;
      }
      if (sky.isWebkit)
        sky.el.style.background = "-webkit-" + val;
    } else {
      //first div is transparent
      if (!sky.isWebkit)
        sky.over.style.background = val;
      else
        sky.over.style.background = "-webkit-" + val;
    };
    sky.over.style.opacity = +!op;
  };

  function setCSS() {
    if (sky.el.parentNode) sky.el.parentNode.style.position = 'relative';
    var hasHeight = parseInt(getComputedStyle(sky.el.parentNode).height) > 0;
    sky.el.style.height = hasHeight ? "100%" : "100vh";
    sky.el.style.overflow = 'auto';
    sky.el.style.width = hasHeight ? "100%" : "100vh";
    sky.el.style.margin = "0";
    sky.el.style.zIndex = -2;
    sky.el.webkitTransform = 'translate3d(0,0,0);'
    sky.el.transform = 'translate3d(0,0,0);'
    sky.over = document.createElement('div');
    sky.el.insertBefore(sky.over, sky.el.firstChild);
    sky.over.setAttribute('style', 'z-index: -1; position: absolute; pointer-events:none; height:100%; width:100%; opacity:1; -webkit-transition : opacity linear ' + sky.speed / 1000 + 's; transition : opacity linear ' + sky.speed / 1000 + 's;');
    if (sky.el === document.body) {
      sky.over.style.position = 'fixed';
      sky.over.style.top = 0;
    }
  }

  sky.stop = function() {
    sky.over.removeEventListener('transitionend', changeOp, false);
  }

  sky.start = function() {
    sky.over.addEventListener('transitionend', changeOp, false);
    changeOp();
  }

  function checkLength(arr) {
    if (arr.length < 13) {
      for (var i = arr.length - 1; i < 13; i++) arr[i] = 0;
    };
  }

  function init(args) {
    for (var a = 0; a < args.length; a++) {
      switch (typeof(args[a])) {
        case "string":
          var getEl = document.getElementById(args[a]);
          sky.el = getEl || document.body;
        case "number":
          sky.speed = args[a];
        case "object":
          if (isArray(args[a])) {
            sky.RGB = args[a];
            checkLength(sky.RGB);
          };
        case "boolean":
          sky.auto = args[a];
      }
    }
    if (!sky.el) sky.el = document.body;
    if (!sky.speed) sky.speed = 9000;
    if (!sky.RGB) sky.RGB = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
    if (sky.auto === undefined) sky.auto = true;
    if (sky.el.style.opacity === undefined) {
      var RGB = sky.RGB;
      sky.el.style.backgroundColor = "rgb(" + (rand(RGB[0]) + RGB[1]) + " ," + (rand(RGB[2]) + RGB[3]) + " ," + rand(RGB[4] + RGB[5]) + ")";
      return;
    }
    setCSS();
    if (sky.auto)
      sky.start();
    setTimeout(changeOp, 200);
  }
  init(arguments);
  return sky;
}

new Sky([255, 120, 255, 120, 255, 120, 255, 120, 255, 120, 255, 120], 5000);
#content{width:100vw; height: 100vh}
<div id="content">Here is some content</div>

You could make an array of images and select a random one with this

var images = ['Imag1','Imag2','Imag3','Imag4',];
var random = images[Math.floor(Math.random() * randomarray.length)];

And then use SetInterval and do the whole process again every 10 seconds or 20 seconds depending on what you want.

May I suggest learning HTML5 Canvas? You will be able to do everything you need + a lot more.

I would try to use pure CSS, i use Javascript to make this kinda of stuff only if there are no other options using CSS.

To prevent this flash on the image version you can preload the images in CSS or using HTML5 prefetch tag.

/* color */
.color {
  animation: colorAnimation 10s infinite;
}

@keyframes colorAnimation {
  0%   { background: red; }
  25%  { background: yellow; }
  50%  { background: blue; }
  75%  { background: green; }
  100% { background: red; }
}

/* image */
.image {
  animation: imageAnimation 10s infinite;
  background-size:     cover;
  background-repeat:   no-repeat;
  background-position: center center; 
}

@keyframes imageAnimation {
  0%   { background-image: url(https://www.w3schools./css/img_mountains.jpg); }
  25%  { background-image: url(https://www.w3schools./css/paris.jpg); }
  50%  { background-image: url(https://www.w3schools./css/lights600x400.jpg); }
  75%  { background-image: url(https://www.w3schools./css/img_5terre_wide.jpg); }
  100% { background-image: url(https://www.w3schools./css/img_mountains.jpg); }
}



/* default block css */
.block {
  position: relative;
  border-radius: 10px;
  --size: 150px;
  height: var(--size);
  width: calc(var(--size) *  3);
}
Color:
<div class="block color"></div>

Image:
<div class="block image"></div>

Here us the code that you can use and customize as per your needs.

 <html lang="en">
<head>
    <script src="http://ajax.googleapis./ajax/libs/jquery/1.7/jquery.js">       </script>

    <script type="text/javascript">
       var num;
       var temp=0;
       var speed=5000; /* this is set for 5 seconds, edit value to suit requirements */
       var preloads=[];

    /* add any number of images here */

    preload(
            'uploads/bg1.jpg',
            'uploads/bg2.jpg',
            'uploads/bg3.jpg'
           );

    function preload(){

    for(var c=0;c<arguments.length;c++) {
       preloads[preloads.length]=new Image();
       preloads[preloads.length-1].src=arguments[c];
      }
     }

    function rotateImages() {
       num=Math.floor(Math.random()*preloads.length);
    if(num==temp){
       rotateImages();
     }
    else {
       document.body.style.backgroundImage='url('+preloads[num].src+')';
       temp=num;

    setTimeout(function(){rotateImages()},speed);
      }
     }

    if(window.addEventListener){
       window.addEventListener('load',rotateImages,false);
     }
    else { 
    if(window.attachEvent){
       window.attachEvent('onload',rotateImages);
      }
     }
    </script>

</head>
<body>

<div>
</div>

</body>
</html>

Change the images path in preload to your images.

发布评论

评论列表(0)

  1. 暂无评论