Javascript 更改CSS背景图像时单击循环不起作用
也许对一个知道自己在做什么的人来说只是个小问题 我想创建如下内容:https://marvelapp.com/404 Gif作为全屏背景加载,当你按下“空格”键时,你会得到另一个Gif,依此类推。看到所有GIF后,循环再次开始 因此,我搜索了如何做到这一点,并找到了这种方法(选项3):https://www.linkedin.com/pulse/20140702040804-99746459-change-css-background-image-with-click (此处也使用:) 在那里,它不与空间,但与鼠标点击什么更好 我试图插入一个while循环,让它与两张以上的图片,但。。。它不起作用,我也不知道为什么 我的做法:Javascript 更改CSS背景图像时单击循环不起作用,javascript,css,loops,while-loop,Javascript,Css,Loops,While Loop,也许对一个知道自己在做什么的人来说只是个小问题 我想创建如下内容:https://marvelapp.com/404 Gif作为全屏背景加载,当你按下“空格”键时,你会得到另一个Gif,依此类推。看到所有GIF后,循环再次开始 因此,我搜索了如何做到这一点,并找到了这种方法(选项3):https://www.linkedin.com/pulse/20140702040804-99746459-change-css-background-image-with-click (此处也使用:) 在那里,
函数updateIndex(){
而(指数<4){
索引++;
}
}指数=0;
bodyObj.onclick=函数(e){
e、 currentTarget.className=类名[索引];
updateIndex();
}
所以我想这更像是一个循环的问题,而不是其他部分的问题
感谢您的帮助或提示:)您不需要循环,请使用“if”(条件结构):
if(索引<4){
索引++;
}否则{
指数=0;
}
while循环将向索引中添加1,直到索引为4,然后将其放回0,以便重新启动
此外,类名(在CSS中)不能以数字开头(如#body.4和#body.5),但必须以字母开头(如#body.img4)我建议使用jQuery,这更简单一些: HTML:
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://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“,//这似乎不是一个有效的映像,但meh
];
指数=0;
$('.backgroundImage')。单击(函数(){
如果(索引<(images.length-1)){//这将使用length-1,因为数组是0索引的。
索引++;
}否则{
指数=0;
}
$(this.css)({
“背景图像”:url(“+图像[索引]+”),
});
});
基本上,我们在这里所做的是在HTML中定义一个起始图像(您也可以使用CSS,正如您所做的那样),然后,单击div时,它只使用CSS根据您定义的数组更改背景图像,而不是更改类。:) 我建议缩进代码,以便更好地了解调用的内容。另外,为什么要在函数调用之外声明索引?为什么不在内部定义它,即
var index=0;虽然…
事实上,for
循环在这里可能是一个更好的方法。我想你没有按照你所期望的方式解释while
循环。while循环中的一切都会立即发生,直到循环顶部的条件为真。这使得你的while循环做的事情与将索引设置为4
一样。是的,“while循环”的意思是“直到满足一个条件为止”。如果你想检查一个条件是否满足,那就是一个简单的“如果”。我想你的意思是“在#body.4
和#body.5
之间”?
if (index < 4) {
index++;
} else {
index = 0;
}
<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>
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] + ")",
});
});