我有这个 preloadimages 功能:
<script type="text/javascript">
function preloadimages(arr){
var newimages=[], loadedimages=0
var postaction=function(){}
var arr=(typeof arr!="object")? [arr] : arr
function imageloadpost(){
loadedimages++
if (loadedimages==arr.length){
postaction(newimages)
}
}
for (var i=0; i<arr.length; i++){
newimages[i]=new Image()
newimages[i].src=arr[i]
newimages[i].onload=function(){
imageloadpost()
}
newimages[i].onerror=function(){
imageloadpost()
}
}
return { //return blank object with done() method
done:function(f){
postaction=f || postaction
}
}
}
preloadimages(['images/image1.jpg','images/image2.jpg','images/image3.jpg']).done(function(images){
})
</script>
这是 changeIm 函数:
<script type="text/javascript">
function changeIm(event){
var code;
if(window.event){
code = event.keyCode;
}
else{
code = event.which;
}
if (code == 49 || code == 97) {
document.getElementById('imageChange').src='image1.jpg';
}
else if (code == 50 || code == 98) {
document.getElementById('imageChange').src='image2.jpg';
}
else {
document.getElementById('imageChange').src='image3.jpg';
}
}
</script>
`
<body>
<form method="post">
<input size="30" type="text" onkeypress="return changeIm(event)" />
</form>
<img src="images/defaultImage.jpg" id="imageChange" alt="Image" />
</body>
为什么不起作用?我也试过:
document.getElementById('imageChange').images[0].src="image1.jpg";
document.getElementById('imageChange').images[0];
这只是工作,但我改变了一些东西,我现在不记得了。我使用此功能通过 onkeypress 事件从键盘更改图像。有什么建议吗?