【发布时间】:2018-06-09 16:03:55
【问题描述】:
这段工作代码(假设 foo/foo_ad1.jpg 到 foo/foo_ad11.jpg 加载到服务器上)从图片库中随机加载一张图片,并每隔几秒用另一张图片替换它。
我试图让图片优雅地淡入淡出,这就是我遇到两个问题的地方:
1) 当我将“this.image”移到 setTimeOut 函数中时,我无法显示它。
2) 我无法让fadeIn() 或fadeOut() 工作,我什至不确定正确的语法是什么。
请查看代码中添加的 cmets。 TY
JS:
Vue.component('foo-ad-module', {
data() {
return {
image: 'foo/foo_ad1.jpg',
timer: '',
x: 0
}
},
created: function() {
this.replaceImage();
this.timer = setInterval(this.replaceImage, parseInt((Math.random() * 33599)%30000) + 5000)
},
methods: {
init(){
this.x = parseInt((Math.random() * 33599)%11) + 1;
this.image = 'foo/foo_ad' + this.x + '.jpg';
console.info("this.image = " + this.image);
},
replaceImage: function() {
this.x = parseInt((Math.random() * 33599)%11) + 1;
//#if
this.image = 'foo/foo_ad' + this.x + '.jpg'; // ...THIS WORKS (when it is outside the setTimeout())
//#else
// $(???).fadeOut("2000"); // ... intending to put a fadeOut() here...
setTimeout(function () {
console.info("this is working...");
// this.image = 'foo/foo_ad' + this.x + '.jpg'; // ... THIS DOESN'T WORK (when it is inside the setTimeout())
// $(???).fadeIn("2000"); // ... intending to put a fadeIn() here...
}, 2000);
//#endif
clearInterval(this.timer)
this.timer = setInterval(this.replaceImage, (parseInt((Math.random() * 33599)%30000) + 5000));
},
},
beforeDestroy() {
clearInterval(this.timer)
},
mounted(){
this.init()
},
template: `
<div class="foo-ad-module " >
<img :src="image" alt="hi there">
</div> `
});
CSS:
.foo-ad-module {
width: 198px;
height: 198px;
border: 1px solid #555;
border-radius: 10px;
margin-bottom: 10px;
}
【问题讨论】:
-
请允许我在 #1 上澄清一点:问题是当 this.image 移动到 setTimeout 内时,它没有任何效果——图片停留在原始图像上,并且不更新。
标签: javascript vue.js fadein fadeout