2016-01-02 122 views
0

可能只是有人谁知道他在做什么有点问题......与点击更改CSS背景图片 - while循环不工作

我想创建这样的事情:HTTPS://marvelapp.com/404 GIF作为全屏背景加载,当你按“空格”时你会得到另一个gif,等等。看完所有gif后,循环再次开始。

所以我搜索如何做到这一点,我发现这种方法(选项3):HTTPS://www.linkedin.com/pulse/20140702040804-99746459-change-css-background-image-with-click (这里也用到了:How to change css background-image on click?) 它不能用于空间,但用鼠标点击甚至更好。

我试图插入一个while循环来得到它有两个以上的图片工作,但...它不工作,我不知道为什么

我的方法:http://jsfiddle.net/h3mfk347/

function updateIndex(){ 
while (index < 4) { 
    index++; 
} 
} index = 0; 
bodyObj.onclick = function(e){ 
e.currentTarget.className = className[index]; 
updateIndex(); 
} 

所以我想这是更多的循环问题比其他部分。

感谢任何帮助或提示:)

+1

我建议缩进你的代码,以获得更好的想法什么时候会被调用.. – towerofnix

+0

此外,为什么你声明索引超出你的函数调用?为什么不在里面定义它,即'var index = 0; while ...' – towerofnix

+1

事实上'for'循环在这里可能是一个更好的方法。 – towerofnix

回答

2

你并不需要一个循环,使用“如果”(有条件的结构):

if (index < 4) { 
    index++; 
} else { 
    index = 0; 
} 

while循环将增加1到索引中,直到索引是4,然后将其重新设置为0,以便重新启动。

而且类名(在你的CSS)不能以数字(如#body.4和#body.5)开始,但必须由字母开头(如#body.img4)

+0

我假设你是指''body.4'和'#body.5'之间的“和”? – towerofnix

+0

是@towerofnix,谢谢 – paulolol

0

我建议你使用jQuery,这是一个有点简单:

HTML:

<script src='path-to-jquery.js'></script> 
<div id="body" class="backgroundImage" style='background-image: url("http://lorempixel.com/300/200/sports/1"); max-width:200px; max-height:200px;'></div> 

的Javascript:

images = [ 
    'http://lorempixel.com/300/200/sports/1', 
    'http://lorempixel.com/300/200/sports/2', 
    'http://lorempixel.com/300/200/sports/3', 
    'http://lorempixel.com/300/200/sports/4', // This seems to not be a valid image, but meh 
]; 

index = 0; 

$('.backgroundImage').click(function(){ 
    if (index < (images.length-1)) { // This uses length-1 because the array is 0-indexed. 
    index++; 
    } else { 
    index = 0; 
    } 
    $(this).css({ 
    'background-image' : "url(" + images[index] + ")", 
    }); 
}); 

http://jsfiddle.net/xp60m5pq/

基本上我们在这里做的是在HTML中定义一个起始图像(您也可以像使用CSS那样使用CSS),然后而不是改变类,当div被点击时只需使用CSS根据您定义的数组更改背景图像。 :)