问题
I have this preloadimages function:
<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>
this is the changeIm function:
<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>
Why doesn't work? Also i tried:
document.getElementById('imageChange').images[0].src="image1.jpg";
document.getElementById('imageChange').images[0];
It is work only ones, but i change something and i don't remember now. I use this function to change images from keyboard with onkeypress event. Any suggestion?
回答1:
preloadimages(['images/image1.jpg','images/image2.jpg','images/image3.jpg']
According to your preloadimages
method, the images are located within a directory images/
However, in your changeIm
method, you're doing this:
document.getElementById('imageChange').src = 'image3.jpg'; // (missing directory)
// Solution: prefix your URLs with "images/":
document.getElementById('imageChange').src = 'images/image3.jpg';
While we're at it, use jQuery to easy implement a cross-browser event handling method:
function changeIm(event) {
var code = event.which
, image
, directory = 'images/';
if (code == 49 || code == 97) {
image = 'image1.jpg';
} else if (code == 50 || code == 98) {
iamge = 'image2.jpg';
} else {
image = 'image3.jpg';
}
$('#imageChange').attr('src', directory + image);
}
$('#changeImgInput').keypress(changeIm);
<input size="30" type="text" id="changeImgInput" />
回答2:
Don't you just need to prefix the changed images with "images/", ex.
document.getElementById('imageChange').src='images/image2.jpg';
来源:https://stackoverflow.com/questions/9446574/onkeypress-changeimage