简体   繁体   English

如何在JavaScript中预加载图像

[英]How to preload images in JavaScript

I need some help preloading images in javascript, here is my code right now. 我需要一些帮助以javascript预加载图像,这是我的代码。 I have to preload the images and then attach a mouseover and mouseout event to them, but preloading is really the only problem I am having right now. 我必须预加载图像,然后将mouseover和mouseout事件附加到它们,但是预加载实际上是我现在遇到的唯一问题。

 "use strict";
 var $ = function(id) { return document.getElementById(id); };

window.onload = function preload() {
var image1 = $("image1");           
var image2 = $("image2");           

// preload images 
var links = $("image_list").getElementsByTagName("a");
var i,link, image;



// attach mouseover and mouseout events for each image
image1.onmouseover = function() {
    "images/release.jpg";
};
image1.onmouseout = function() {

};

image2.onmouseover = function() {

};
image2.onmouseout = function() {

};
};

Blockquote Here is the HTML Blockquote这是HTML

<!DOCTYPE html>
<html>
<head>
<title>Image Rollover</title>
<link rel="stylesheet" type="text/css" href="rollover.css">
<script type="text/javascript" src="rollover.js"></script>
</head>

<body>
<main>
    <h1>Fishing Images</h1>
    <p>Move your mouse over an image to change it and back out of the
        image to restore the original image.</p>
    <ul id="image_list">
        <li><a href="images/release.jpg" id="catch" title="Catch and 
    Release"></a></li>
        <li><a href="images/deer.jpg" title="Deer at Play"></a></li>
        <li><a href="images/hero.jpg" title="The Big One!"></a></li>
        <li><a href="images/bison.jpg" title="Grazing Bison"></a></li>
    </ul>
    <p>
        <img id="image1" src="images/hero.jpg" alt="">
        <img id="image2" src="images/bison.jpg" alt="">
    </p>
    </main>
    </body>
    </html>

` `

You can do that binding the event onload 您可以绑定事件onload

image2.onload = function(){
    image2.onmouseover = function() {

    };
    image2.onmouseout = function() {

    };
}

If you want to wait for all images to load you can do it with jQuery 如果要等待所有图像加载,则可以使用jQuery完成

$(window).on("load", function() {
    //This will be executed when every single DOM element is loaded
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM