防止图片未找到时img标签的alt文本旋转

5

我在图片上应用了transform: rotate(90deg);的CSS样式,但同时也旋转了ALT文本,导致当图片未能正确显示时,此文本会出现在其他图片之上。

有没有什么方法可以防止ALT文本被旋转呢?

<div>
<img style="transform: rotate(90deg);" alt="User Name" src="http://ImageURL">
</div>

ALT text

div { margin-top:50px; }
<div>
    <img style="transform: rotate(90deg);" alt="User Name" src="http://ImageURL">
    </div>

编辑

我的页面上有许多图片。

在页面中有大量的图片。

3个回答

4
您可以使用onerror处理程序从图像中删除样式:

function onImageNotFound() {
  document.getElementById('imgTest').style.transform = 'none';
}
div { margin-top:50px; }
<div>
    <img id="imgTest" style="transform: rotate(90deg);" alt="User Name" src="http://ImageURL" onerror="onImageNotFound();">
</div>

这里是内联版本:

div { margin-top:50px; }
<div>
    <img style="transform: rotate(90deg);" alt="User Name" src="http://ImageURL" onerror="this.style.transform = 'none';">
</div>


这是一个有趣的想法,但当图像获取或呈现缓慢时,alt 文本也可能会显示出来。 我更愿意使用 onerror 回调来添加替代文本(作为丰富元素)。 - Denys Séguret
那不是最常见的情况,但它确实会发生,这就是它的设计方式。请参见MDN(https://developer.mozilla.org/en-US/docs/Web/HTML/Element/img):“或者如果图像尚未下载”。 - Denys Séguret
@klugjo谢谢回复,但MDN文章说“不要使用onerror方法”... 我应该遵循它吗? - nbi
@nbi https://developer.mozilla.org/zh-CN/docs/Mozilla/Tech/XUL/image 我在 MDN 上没有看到任何内容。 - klugjo
@klugjo https://developer.mozilla.org/zh-CN/docs/Web/HTML/Element/img#浏览器兼容性 - nbi
你说得对。目前我还不知道其他的解决方案... https://dev59.com/tHVD5IYBdhLWcg3wGHeu. 我所做的似乎也是其他人都在做的。你可以看看jQuery。 - klugjo

2

最佳解决方案可能是仅在已加载的图像上应用转换:

for (let img of document.querySelectorAll("img")) {
  img.addEventListener("load", function(){
    this.classList.add("rotated");
  });
}
div { margin-top:50px; }
.rotated { transform: rotate(90deg); }
<div>
    <img alt="User Name" src="http://ImageURL">
</div>
<div>
    <img alt="User Name" src="https://dystroy.org/spacebullet-48.png">
</div>


2

如果你只是针对一张(小)图片应用效果,你可以使用CSS来实现。

在旋转的图像后面放置一个未旋转的副本。如果图像加载成功,则会显示旋转版本。如果失败,则会显示未旋转版本的alt文本。

div {
  margin-bottom: 50px;
  border: 1px solid red;
  position: relative;
  /* hide the broken image icon */
  overflow: hidden;
}

img {
  display: inline-block;
  vertical-align: bottom;
}

.img-rotate {
  transform: rotate(90deg);
  /* hide the alt text */
  color: transparent;
}

.img-copy {
  position: absolute;
  left: 0;
  z-index: -1;
}
<p>Broken image link</p>
<div>
  <img class="img-rotate" alt="User Name" src="http://ImageURL">
  <img class="img-copy" alt="User Name" src="http://ImageURL">
</div>

<p>Working image link</p>
<div>

  <img class="img-rotate" alt="User Name" src="https://unsplash.it/200">
  <img class="img-copy" alt="User Name" src="https://unsplash.it/200">
</div>


这在大图像上应该是一样的:它们已经被缓存了,所以这对浏览器来说不应该是一个负担。 - Denys Séguret
@DenysSéguret 所以浏览器只会为具有相同src属性的两个或更多<img>元素进行一次调用? - nbi
@nbi 对的。DOM 仍然有点重,但如果您无法使用 JavaScript 的 onload 事件处理程序,则这看起来是一个不错的解决方案。 - Denys Séguret

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接