Is there way to change the image src
attribute with its alt
attribute on load of the image?
I want the script to automatically change the image's source to the image's alt.
Before
<img src="" alt="exe">
After
<img src="exe" alt="exe">
You could use JavaScript:
// Execute function on load through self-invocation
var switchAlt = function() {
// Get all images on the document
var images = document.getElementsByTagName('img');
// Count the number of image elements and switch alt and src
var i = images.length;
while (i--) {
images[i].src = images[i].alt;
}
}();
Don't forget to wrap it into script tags if you're implementing it in HTML files:
<script type="text/javascript">
// Execute function on load through self-invocation
var switchAlt = function() {
// Get all images on the document
var images = document.getElementsByTagName('img');
// Count the number of image elements and switch alt and src
var i = images.length;
while (i--) {
images[i].src = images[i].alt;
}
}();
</script>
Try this:
var change = function() {
var imgs = document.images || document.getElementsByTagName('img');
for (var i = 0; i < imgs.length; i++) {
imgs[i].src = imgs[i].alt;
}
}
First of all, give the id of the image so img tag will look like this:
<img id="img1" src="" alt="myimage.jpg" onload = "changesource()"/>
Now write a JavaScript function like this:
function changeSrc()
{
var img = document.getElementById("img1");
img.src =img.alt;
}
Now call this function on the load of image like this:
onload = "changeSrc()"
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.