Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/81.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Jquery 我想每5秒钟更改一个div的背景图像_Jquery_Html_Slideshow - Fatal编程技术网

Jquery 我想每5秒钟更改一个div的背景图像

Jquery 我想每5秒钟更改一个div的背景图像,jquery,html,slideshow,Jquery,Html,Slideshow,大家好,我正在尝试每5秒钟更改一个div的背景图像,并重复这些图像。使用简单的html,比如带有类和id的div <body> <div class="background-rep" style="max-width:500px"> <p>The slides </p> </div> <script> var myIndex = 0; carousel(); function carousel() {

大家好,我正在尝试每5秒钟更改一个div的背景图像,并重复这些图像。使用简单的html,比如带有类和id的div

 <body>

<div class="background-rep" style="max-width:500px">
  <p>The slides </p>


</div>

<script>
var myIndex = 0;
carousel();

function carousel() {
    var i;
    var y =["img_rr_01.jpg" , "img_rr_02.jpg" , "img_rr_03.jpg", "img_rr_04.jpg" ];
    var x = document.getElementsByClassName("background-rep");
    for (i = 0; i < y.length; i++) {
       x.style.backgroundImage = url(y[i])";  
    }
    myIndex++;
    if (myIndex > y.length) {myIndex = 1}    
    x.style.backgroundImage = "block";  
    setTimeout(carousel, 9000);    
}
</script>

</body>

幻灯片

var-myIndex=0; 转盘(); 函数旋转木马(){ var i; 变量y=[“img_rr_01.jpg”、“img_rr_02.jpg”、“img_rr_03.jpg”、“img_rr_04.jpg”]; var x=document.getElementsByClassName(“后台代表”); 对于(i=0;iy.length){myIndex=1} x、 style.backgroundImage=“block”; 设置超时(旋转木马,9000); }
我尝试了stackoverflow的一些解决方案,但效果不好
谢谢这里有几个问题。首先:获取元素应该是

var x = document.querySelector('.background-rep');
接下来,您的循环当前会导致设置数组中的最后一个图像,以及不正确的语法。我想您正在寻找:

x.style.bacgkroundImage = "url(" + y[myIndex] + ")";
您还应该去掉行
x.style.background=“block”
,因为这将覆盖新设置的背景图像

同样对于5秒的间隔,您的
设置超时值应为5000,因为它是以毫秒为单位测量的:

setTimeout(carousel, 5000);  

你尝试了什么解决方案?你能发布代码吗?图像标签在哪里?那么你尝试了什么?@MattL。这是我的attempt@yuvrajprogrammer正如我所说,我想更改一个div的背景图像,但仍然没有得到任何东西。得到的解决方案只是在尝试使用这个时遇到了一个问题。css({backgroundImage:'url('+images[++currentImage]+'))我想用css制作重要的背景图像我怎么能这样做呢?只需在url之后添加!important:
.css({backgroundImage:'url('+images[++currentImage]+')!important'})