jQuery 重复循环数组来更改标签属性
我正在制作一个简单的滑块,它通过更改 img
标记的 src
属性和锚标记的属性来工作。这就是我到目前为止所想到的:
(function($){
var slides = [
'http://placehold.it/801x350',
'http://placehold.it/802x350',
'http://placehold.it/803x350'
],
titles = [
'Title 1',
'Title 2',
'Title 3'
],
links = [
'http://test1.com',
'http://test2.com',
'http://test3.com'
],
image = $('#stretch-img'),
anchor = $('.featured-title>h2>a');
var interval = setInterval(function() {
image.attr('src', slides[0]);
anchor.attr('href', links[0]);
anchor.html(titles[0]);
}, 3000);
})(jQuery);
我希望间隔能够通过简单的淡入淡出效果连续循环遍历数组。什么是最好的方法来做到这一点或任何真正做到这一点的方法,因为我没有。
谢谢!
我感谢所有的帮助。
I am making a simple slider that works by changing the src
attribute of an img
tag and the attributes of anchor tags. This is what I have come up with so far:
(function($){
var slides = [
'http://placehold.it/801x350',
'http://placehold.it/802x350',
'http://placehold.it/803x350'
],
titles = [
'Title 1',
'Title 2',
'Title 3'
],
links = [
'http://test1.com',
'http://test2.com',
'http://test3.com'
],
image = $('#stretch-img'),
anchor = $('.featured-title>h2>a');
var interval = setInterval(function() {
image.attr('src', slides[0]);
anchor.attr('href', links[0]);
anchor.html(titles[0]);
}, 3000);
})(jQuery);
I want the interval to loop through the arrays continuously with a simple fade effect. What can be the best way to do this or any way to do this really, coz I've got none.
Thanks!
I appreciate all the help.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
要循环遍历数组,您可以设置一个当前位置变量和一个保存数组长度的变量:
然后要淡出,您可以淡出,更改源,然后淡入:
这可能会导致当
fadeIn(500)
启动时,图像未完全加载,这可以通过使用附加到image
load
事件的事件处理程序来修复/code> 元素:然后你可以删除
fadeIn(500)
来自间隔函数,因为它会在图像加载时触发。每当图像源发生更改且新源完成加载时,load
事件就会触发。请注意,
.on()
是 jQuery 1.7 中的新增功能,在本例中与.bind()
相同。To loop through your array you can set a current-position-variable and a variable that saves the length of the array:
Then to fade you can fade-out, change the source, then fade-back-in:
This can lead to the image not quite being loaded when the
fadeIn(500)
kicks-in, which can be fixed by using an event handler attached to theload
event for theimage
element:Then you can remove the
fadeIn(500)
from the interval function since it will fire when the image has loaded. Theload
event will fire whenever the source of the image changes and the new source finishes loading.Note that
.on()
is new in jQuery 1.7 and is the same as.bind()
in this case.