我目前正在使用单选按钮和复选框来显示基于值的图像。我注意到图像在开始时加载缓慢。例如,使用“display:none”预先创建了图像元素(已经设置了src属性),那么我唯一需要做的就是使用display属性。有没有预装图像? EXAMPLE
JS
<script>
function check_value(currentElement, val, id, type) {
var el = document.getElementById("imgBox" + id);
if (val > 0 && val < 4) { //will trigger when [1,2,3]
if(currentElement.checked)
{
el.src = "images/" + type + val + ".jpg";
el.style.display = "";
}
else
{
el.src = "";
el.style.display = "none";
}
}
}
</script>
HTML
<h2>Choose a bike</h2>
<form name="builder">
<input type="radio" name="field" onclick='check_value(this, 1, 1, "bike")'/> KAWASAKI KX 450F<br />
<input type="radio" name="field" onclick='check_value(this, 2, 1, "bike")'/> 2010 Yamaha Road Star S<br />
<input type="radio" name="field" onclick='check_value(this, 3, 1, "bike")'/> Aprilia RSV4<br />
</form>
答案 0 :(得分:1)
是的!如果你有JQuery,预加载图像真的很容易:
$.fn.preload = function() {
this.each(function(){
$('<img/>')[0].src = this;
});
}
$(['some-image.gif']).preload();
同时检查此资源:http://perishablepress.com/3-ways-preload-images-css-javascript-ajax/
答案 1 :(得分:0)
这是我前段时间为自己制作的一项功能:http://pastebin.com/GeBawE8r
您可以按如下方式使用它:
var loader = new imagePreloader();
// Object containing the names of the imgs as keys and url as values
loader.list = {name: "url"...};
// function to call when done loading everything
loader.onload = ...
// function to call at each time it loades a single image of the list
loader.each = ...
// function to call when unable to load one of the images
loader.onerror = ...
// set this to true to continue even if some of the images fail to load
loader.ignoreErrors = true/false
// Starts loading the images
loader.load();
完成加载后,属性ready
将设置为true,您可以访问list
对象中的图片。
if(loader.ready)
alert(loader.list.myImageName); // Image object