有没有办法在加载图像时使用其 alt
属性更改图像 src
属性?
我希望脚本自动将图像的源更改为图像的 alt。
之前
<img src="" alt="exe">
之后
<img src="exe" alt="exe">
最佳答案
你可以使用 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>
关于javascript - 如何使用 alt 更改 img 的 src?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4841400/