简体   繁体   中英

Replacing a broken image and resizing the error image with javascript

OK so I know this question has been asked separetly but I'm trying to use javascript to replace a broken image with another image with DIFFERENT dimensions by changing th src attribute. Here's a part of my code:

MARKUP:

...
<img id="error-img" class="img-header" onerror="imgError(this);" alt="Header" src="images/header.png">
...

STYLES:

...
.img-header { width: 54px; height: 64px; }
...

JAVASCRIPT:

...
function imgError(image) {
image.onerror = "";
image.src = "/images/broken.png";
return true;
}
...

So what I need is to include a piece of code in this function so that when the image gets replaced the new image has it's dimensions set correctly but not 54x64px.

EDIT:

Thank you for the answers guys but I've forgot to mention the size of the broken.png image: Width: 276px Height: 45px.

...
function imgError(image) {
image.onerror = "";
image.src = "/images/broken.png";
// set width/height
image.style.width = "50px";
image.style.height = "50px";
// or add class name
image.className = "img-error";
return true;
}
...

CSS

...
.img-header { width: 54px; height: 64px; }
.img-error  { width: 40px; height: 40px; }
...

If you want replacement image to have it's own width/height and not inherited from .image-header class, you have couple options:

1). clear className:

image.className = '';

http://jsfiddle.net/gGP5D/

2). add new class name:

function imgError(image) {
    image.onerror = "";
    image.src = "/images/broken.png";
    image.className += ' replacement-image';
}

http://jsfiddle.net/gGP5D/1/

This new class name could define new dimensions if they are known, or reset width and height to auto values.

You can do the following to reset the image's CSS properties to whatever size your error image is:

function imgError(image) {
  image.onerror = "";
  image.src = "/images/broken.png";
  elem.style.width = "100px"; //use whatever size the new image is here
  elem.style.height= "100px"; //use whatever size the new image is here
  return true;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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