简体   繁体   English

jQuery图像src每8秒更改一次

[英]jQuery image src change every 8 seconds

I have a div with the ID of header, what id like is the first image found in this id to change every 8 seconds. 我有一个标题ID的div,id是这个id中第一个每8秒更改一次的图像。 The image name is image1.jpg and after 8 seconds id like it to change image1 to image2 then after another 8 seconds revert back to image1 and so forth. 图像名称是image1.jpg,并且在8秒之后id将它改变为image1然后在另外8秒之后恢复到image1,依此类推。

Is the route of finding the first image in the div etc a bit long winded and how would i go about the rest? 在div中找到第一张图像的路线是否有点长,我将如何处理其余的? For instance getting the src to change every 8 seconds? 例如让src每8秒更换一次? Help much appreciated 非常感谢

You can try 你可以试试

var $img = $('div#header img').first();
var flag = false;
setInterval(function(){
    $img.attr('src', 'image' + (flag ? 1 : 2) + '.jpeg' );
    flag = !flag;
}, 8000);

Functional Demo: Fiddle (Note: This does not work with image, but just a demo for the technique used. Check the console to see the src value) 功能演示: 小提琴 (注意:这不适用于图像,但只是所用技术的演示。请检查控制台以查看src值)

assuming the first image is image1.jpeg then at the first run you what it to be 2 so use ++i to increment first then use the var in the string 假设第一个图像是image1.jpeg然后在第一次运行时你得到它是2所以使用++i先增加然后使用字符串中的var

var i = 0;
setInterval(function() { 
     if(i == 2) i=0;

     $('#imageID').attr('src', 'image' + (++i) + '.jpeg' );
}, 8000);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM