javascript - 如何找到与替代文本和框模型相关的另一个 Safari 解决方法?
问题描述
由于一些当之无愧的反对票,这个问题已经得到了认真的检查。(学过的知识 :))
场景:我在 CMS 上工作,用户可以在其中添加style
宽度和高度或添加alt
到img
标签。我们通常将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 中工作
解决方案
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>
推荐阅读
- firebase - Firebase 令牌 ID:通过 WorkManager Android 传递时
- html - 如何使多个 SVG 内联?
- php - MongoDB PECL 驱动程序和 Composer PHPLIB 之间的区别?
- python - 如何在散景图中旋转箭头标记以显示风速方向?
- java - RDDs如何为自己拆分数据?
- ruby-on-rails - 设置to_param方法后无法创建嵌套资源
- ios - 如何获取我的 iOS 应用程序的本地化语言?
- python - python中的平均风数据(每小时10-10分钟)
- css - 如何从 CSS font-family 列表中知道浏览器使用哪种字体?
- firebase - 建立 Firebase 聊天室数据库很热门?