我想在 setInvterval 中更改 div 的背景图像,但不知道如何做。这是代码:
$('.thumbnail').on({
'mouseenter': function(){
var thumbs = $(this).attr('data-num-thumbs');
var thumb_url = $(this).css('background-image');
console.log(thumb_url);
var i = 1;
setInterval(function(){
var new_thumb_url = thumb_url.replace(/\d{1,2}\.jpg/gi, i + '.jpg');
console.log(new_thumb_url);
$(this).css('background-image', new_thumb_url);
i++;
if(i > 10) i = 1;
}, 3000);
});
});
这是 div
的样子:
<div data-num-thumbs="17" class="thumbnail" style="background: url('http://site/img/11.jpg') no-repeat;"></div>
最佳答案
看起来 setInterval()
中的 $(this)
正在映射到其他东西,试试这个
$('.thumbnail').on({
'mouseenter': function(){
$this=$(this); //store $(this) in a local var
var thumbs = $(this).attr('data-num-thumbs');
var thumb_url = $(this).css('background-image');
console.log(thumb_url);
var i = 1;
setInterval(function(){
var new_thumb_url = thumb_url.replace(/\d{1,2}\.jpg/gi, i + '.jpg');
console.log(new_thumb_url);
//$(this).css('background-image', new_thumb_url);
$this.css('background-image', new_thumb_url);
i++;
if(i > 10) i = 1;
}, 3000);
}
});
快乐编码:)
关于javascript - 背景图片不会改变,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21853465/