使用jquery更新了多个背景

时间:2016-01-27 19:14:58

标签: jquery html css

我对css和各种JavaScript库有一些经验,但我一直在努力将多个背景合并到我下载的代码中http://codepen.io/quasimondo/pen/lDdrF。我想在动画渐变之上抛出一个透明的.png。

我尝试将png附加到网站的不同部分(正文,div),这似乎无法正常工作,因为我失去了对它的一些更好的控制。每当我尝试添加到$('#grad'')。css函数时,它都会出错。我假设这是一个简单的语法问题,但我不知道。

谢谢你的期待。这是我的第一篇文章,我搜索过以前的帖子。如果我错过了什么,抱歉。

杰森

HTML

<!DOCTYPE html>
<title>Animated Background Gradient</title>
<body>
<div id="gradient" />
</body>   
<script src="js/index.js"></script>

的CSS

body{
background-color: #000000;
padding: 0px;
margin: 0px;
}

#gradient {
width: 100%;
height: 800px;
padding: 0px;
margin: 0px;}

JS

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;
var colorIndices = [0,1,2,3];

var gradientSpeed = 0.0006;

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];

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);

https://jsfiddle.net/byjrglass/f7vsLss1/7/

1 个答案:

答案 0 :(得分:0)

您必须考虑到CSS Gradients的行为与图像相似。例如,这个:

background: linear-gradient(to bottom, blue, white);

产生与此相同的东西:

background-image: linear-gradient(to bottom, blue, white);

因此,要在其上使用png图像,您需要执行以下操作:

background-image: url(image.png), linear-gradient(to bottom, blue, white)

使用您的代码,例如:http://codepen.io/anon/pen/WrJOQL

或者您可以将渐变放在正文中,而不是放在div中,并将图像包含在div中。以下是使用您的代码的示例:http://codepen.io/anon/pen/gPzWVo