是否有办法在图片加载时使用src
属性更改图片alt
属性?
我希望脚本自动将图像的源更改为图像的alt。
之前
<img src="" alt="exe">
后
<img src="exe" alt="exe">
答案 0 :(得分:3)
您可以使用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;
}
}();
如果您在HTML文件中实现它,请不要忘记将其包装到脚本标记中:
<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>
答案 1 :(得分:1)
试试这个:
var change = function() {
var imgs = document.images || document.getElementsByTagName('img');
for (var i = 0; i < imgs.length; i++) {
imgs[i].src = imgs[i].alt;
}
}
<强> DEMO 强>
答案 2 :(得分:0)
首先,给出图像的id,以便img标签看起来像这样:
<img id="img1" src="" alt="myimage.jpg" onload = "changesource()"/>
现在编写一个这样的JavaScript函数:
function changeSrc()
{
var img = document.getElementById("img1");
img.src =img.alt;
}
现在在图像加载上调用此函数,如下所示:
onload = "changeSrc()"