Automatically load an image using javascript

2019-05-22 18:14发布

I'm using this code to build a gallery:

        window.onload=function(){
        var image = document.getElementsByClassName('thumbnails')[0].getElementsByTagName('img');
        var mainImage = document.getElementById('rr_lrg_img'); 

        [].forEach.call(image,function(x){ 
            x.onmouseover = function(){
                 mainImage.src = x.src; 
             };
        });
        }

The code loads different thumbnails on the big image when "onmouseover". Now I would like to "preload" the first image from that gallery of thumbnails. I tried using onload with

rr_lrg_img.src=document.getElementsByClassName('thumbnails')[0].getElementsByTagName('img')[0].src

but then it conflicts with the onmouseover. Any ideas? I can only use javascript, no jquery.

1条回答
爷的心禁止访问
2楼-- · 2019-05-22 18:45

Since your var image is actually a collection of images, you need to use the [0] index pointer to target the first one:

window.onload=function(){
  
  var image = document.getElementsByClassName('thumbnails')[0].getElementsByTagName('img');
  var mainImage = document.getElementById('rr_lrg_img'); 
  
  mainImage.src = image[0].src; // Add this line (preload first image into main one)
  
  function toMainImage() {
     mainImage.src = this.src; 
  }

  [].forEach.call(image,function(x){
    x.addEventListener("mouseenter", toMainImage, false);
  });
  
}
.thumbnails img{height:50px;}
<img src="//placehold.it/200x200&text=default" id="rr_lrg_img">

<div class="thumbnails">
  <img src="//placehold.it/200x200/cf5&text=1">
  <img src="//placehold.it/200x200/f0f&text=2">
  <img src="//placehold.it/200x200/444&text=3">
</div>

查看更多
登录 后发表回答