使用javascript自动加载图像 [英] Automatically load an image using javascript

查看:71
本文介绍了使用javascript自动加载图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用以下代码来建立画廊:

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; 
             };
        });
        }

当鼠标悬停"时,代码会在大图像上加载不同的缩略图.现在,我想预加载"该缩略图库中的第一张图像.我尝试将onload与

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

,但是它与onmouseover冲突.有任何想法吗?我只能使用javascript,不能使用jquery.

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

推荐答案

由于您的var image实际上是图像的集合,因此需要使用[0]索引指针定位第一个图像:

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>

这篇关于使用javascript自动加载图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆