我如何使用 JavaScript 获得适用于最新版本 Internet Explorer 的自动渐变背景?

How could I have an auto-gradient background using JavaScript that works with latest version of Internet Explorer?

很久以前我在 Codepen 的自动渐变背景

上找到了这个例子
var colors = new Array(
 [62,35,255],
 [60,255,60],
 [255,35,98],
 [45,175,230],
 [255,0,255],
 [255,128,0]);

var step = 0;
//color table indices for: 
// current color left
// next color left
// current color right
// next color right
var colorIndices = [0,1,2,3];

//transition speed
var gradientSpeed = 0.002;

function updateGradient()
{

  if ( $===undefined ) return;

var c0_0 = colors[colorIndices[0]];
var c0_1 = colors[colorIndices[1]];
var c1_0 = colors[colorIndices[2]];
var c1_1 = colors[colorIndices[3]];

var istep = 1 - step;
var r1 = Math.round(istep * c0_0[0] + step * c0_1[0]);
var g1 = Math.round(istep * c0_0[1] + step * c0_1[1]);
var b1 = Math.round(istep * c0_0[2] + step * c0_1[2]);
var color1 = "rgb("+r1+","+g1+","+b1+")";

var r2 = Math.round(istep * c1_0[0] + step * c1_1[0]);
var g2 = Math.round(istep * c1_0[1] + step * c1_1[1]);
var b2 = Math.round(istep * c1_0[2] + step * c1_1[2]);
var color2 = "rgb("+r2+","+g2+","+b2+")";

 $('#gradient').css({
   background: "-webkit-gradient(linear, left top, right top, from("+color1+"), to("+color2+"))"}).css({
    background: "-moz-linear-gradient(left, "+color1+" 0%, "+color2+" 100%)"});

  step += gradientSpeed;
  if ( step >= 1 )
  {
    step %= 1;
    colorIndices[0] = colorIndices[1];
    colorIndices[2] = colorIndices[3];

    //pick two new target color indices
    //do not pick the same as the current one
    colorIndices[1] = ( colorIndices[1] + Math.floor( 1 + Math.random() * (colors.length - 1))) % colors.length;
    colorIndices[3] = ( colorIndices[3] + Math.floor( 1 + Math.random() * (colors.length - 1))) % colors.length;

  }
}

setInterval(updateGradient,10);

但是它在 Internet Explorer 上不起作用。由于工作需要用到,但对JavaScript了解不够,请问有什么好的可以实现吗?

你的问题是你的代码使用了vendor-prefixed properties,所以这段代码:

$('#gradient').css({background: "-webkit-gradient(linear, left top, right top, from("+color1+"), to("+color2+"))"}).css({background: "-moz-linear-gradient(left, "+color1+" 0%, "+color2+" 100%)"});

应该改成这样:

$('#gradient').css({background: "-webkit-gradient(linear, left top, right top, from("+color1+"), to("+color2+"))"}).css({background: "-moz-linear-gradient(left, "+color1+" 0%, "+color2+" 100%)"}).css({background: "linear-gradient(left, "+color1+" 0%, "+color2+" 100%)"}).css({background: "-ms-linear-gradient(left, "+color1+" 0%, "+color2+" 100%)"});

请看:http://caniuse.com/#search=linear-gradient

所有现代浏览器都使用此 CSS 语法:

background: linear-gradient(to right, rgba(255, 0, 0, 1.0), rgba(0, 0, 0, 1.0));

我认为将您的代码更改为这样应该可以在现代浏览器中运行:

$('#gradient').css({
   background: "linear-gradient(to right, "+color1+" 0%, "+color2+"  100%)"});

这应该适用于:

  • IE10+
  • Chrome 26+
  • 火狐 16+
  • 野生动物园 6.1+