[英]How to preload images in JavaScript
我需要一些帮助以javascript预加载图像,这是我的代码。 我必须预加载图像,然后将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这是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>
`
您可以绑定事件onload
image2.onload = function(){
image2.onmouseover = function() {
};
image2.onmouseout = function() {
};
}
如果要等待所有图像加载,则可以使用jQuery完成
$(window).on("load", function() {
//This will be executed when every single DOM element is loaded
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.