Javascript图像src没有改变

时间:2018-04-16 01:38:57

标签: javascript html dom

我试图让图像每两秒在两个来源之间切换,但图像不会改变

<img id="bannerPic" src="banner1.jpg">
<script>
var pic = document.getElementById('bannerPic').src;
setInterval(function(){
if(pic == 'banner1.jpg'){
pic = 'banner2.jpg';
console.log('change1');
}
else{
pic = 'banner1.jpg';
console.log('change2');
}
}, 2000);
</script> 

2 个答案:

答案 0 :(得分:5)

您正在为变量而不是属性src分配值。

您需要将新值设置为属性src

要检查当前网址,请使用以下网址:img.src.indexOf('banner1.jpg')

&#13;
&#13;
var img = document.getElementById('bannerPic');
setInterval(function() {
  if (img.src.indexOf('banner1.jpg') !== -1) {
    img.src = 'banner2.jpg';
    console.log('change1');
  } else {
    img.src = 'banner1.jpg';
    console.log('change2');
  }
}, 2000);
&#13;
<img id="bannerPic" src="banner1.jpg">
&#13;
&#13;
&#13;

答案 1 :(得分:1)

&#13;
&#13;
<img id="bannerPic" src="banner1.jpg">
<script>
var pic = document.getElementById('bannerPic')
console.log(pic.src)
setInterval(function(){
if(pic.src == 'https://stacksnippets.net/banner1.jpg'){
pic.src = 'https://stacksnippets.net/banner2.jpg';
console.log('change1');
}
else{
pic.src = 'https://stacksnippets.net/banner1.jpg';
console.log('change2');
}
}, 2000);
</script> 
&#13;
&#13;
&#13;