防止在找不到图像时旋转img标记的替代文本

时间:2018-05-11 05:56:00

标签: html css

我在我的图片上应用了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 个答案:

答案 0 :(得分:3)

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

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

这是一个内联版本:

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

答案 1 :(得分:2)

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

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

答案 2 :(得分:2)

如果您只将效果应用于一个(小)图像,则可以使用CSS执行此类操作。

在旋转的图像后面放置未旋转的图像副本。如果图像加载,则会显示旋转的版本。如果失败,将显示非旋转版本的替代文字。

&#13;
&#13;
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;
}
&#13;
<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>
&#13;
&#13;
&#13;