首页 > 解决方案 > 如何找到与替代文本和框模型相关的另一个 Safari 解决方法?

问题描述

由于一些当之无愧的反对票,这个问题已经得到了认真的检查。(学过的知识 :))

场景:我在 CMS 上工作,用户可以在其中添加style宽​​度和高度或添加altimg标签。我们通常将img标签放在一个picture标签中,figure但即使这样也不能保证。我们通过将它们存储在可能大小的数组中来优化这些图像。因此,src直到我们对 进行计算以确定要在该属性img中加载的图像之前,才知道 。src

<picture>
  <img src='' alt='a long alt text' class='imageWithAlt'>
</picture>

在 Safariconsole.log中,宽度约为 92。

问题:就我们而言,92 可能是替代文本,也可能是'style=width: 92px'用户决定应用的。

技巧:为了更好地了解宽度,我们会去掉alt

$element.attr('alt', '').css({ margin: 0, padding: 0 }); 

然后 a$element.width();将给出不带 alt 文本的宽度。如果该数量小于我们的魔法40px,那么我们将寻找填充父容器。至少我们曾经使用过这个 Hack,直到我不知道 Safari 什么时候现在只是让它成为盒子模型,alt而不关心它以后是否被删除。所以现在这个例子将跳过我们对父容器的检查,并呈现比用户预期的更小的图像版本。

问题:在 Safari 中是否还有其他任何人都能想到的解决方法?

示例 HTML:

<figure>
  <picture>
    <img src='' alt='a long alt text' class='imageWithAlt'>
  </picture>
  <picture>
    <img src='' alt=''  class='imageWithNoAlt'>
  </picture>
</figure>

示例 JavaScript:

let imgWithAlt = $('img')[0],
    imgWithNoAlt = $('img')[1];

console.log('imgWithAlt width: ', imgWithAlt.width);
console.log('imgWithNoAlt width: ', imgWithNoAlt.width);

// previous solution to get width or height without alt text
imgWithAlt.removeAttribute('alt');

console.log('imgWithAlt width after removing alt: ', 
imgWithAlt.width);

示例 CSS:

img {
  background: #eee;
}

figure {
  width: 480px;
  height: 270px;
}

这是jsfiddle 的链接,如果您在 Safari 中使用,您会看到不同之处,在 Chrome 中,我们有办法阻止当前显示的 16X16 图标,因此我们的 Hack 将在 Chrome 中工作

标签: javascriptjqueryhtmlcss

解决方案


Alt 包含 W x H 作为文本

<img src="img/hero.jpg" id="image" alt="">
<script>
var img, width, height;
img = document.getElementById("image");
width  = img.width;
height = img.height;
img.alt = width + ' x ' + height;
</script>

推荐阅读