javascript - 以不会导致浏览器因低速连接而回流的方式定义响应式图像(首选 HTML)

标签 javascript html css

对于我的网络应用程序,我希望提供给用户的图像具有响应性。此外,我还想在图像标签中指定 widthheight 属性,这样在移动连接速度较慢的情况下,就不会出现浏览器重排。

是否可以通过使用纯 HTML 来满足两者这些要求?

如果确实有可能,我们非常欢迎提供展示工作示例的说明性答案。也欢迎次要的纯 JS(无库)答案(但我的主要重点是通过轻量级 HTML 来实现)。

注意:来自类似问题的这个 accepted answer 依赖于 JQuery(我不精通),因此不符合我的要求。


背景:对于移动响应式设计,通常指定宽度(或最大宽度),并将高度定义为auto。这将与 widthheight 值发生冲突(并且与之相反)。因此我的问题。

最佳答案

就其值(value)而言,这是 that jQuery answer 的原始版本。

// convert nodelist into array:
var imageList = Array.prototype.slice.call(
  document.getElementsByTagName('img')
);

imageList.forEach(function(img) {
  // only act on images with set w+h attributes:
  if (img.getAttribute("width") && img.getAttribute("height")) {
    // calculate the desired height (in pixels)
    var scaledHeight = img.getAttribute("height") * img.clientWidth / img.getAttribute("width");

    // wrap the image in an element with that height
    var wrapper = document.createElement('span');
    wrapper.setAttribute("style", "height: " + scaledHeight + "px; display: inline-block");
    img.parentNode.insertBefore(wrapper, img);
    wrapper.appendChild(img);
  }
});
img {
  max-width: 100%;
  height: auto;
}

/* Just so you can see what it's doing: */
span {border:1px solid}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img src="http://placehold.it/2500x100" width="2500" height="100">
<img src="http://placehold.it/1000x300" width="1000" height="300">
<img src="http://placehold.it/100x100" width="100" height="100">
<img src="http://placehold.it/100x100">

为了更加完整,上面的 jQuery 版本与原始答案不同,它可以正常工作。 (较旧的答案可能取决于未显示的 CSS,或者自编写以来发生了其他变化,或者只是错误的;无论如何,它增加了太多的填充。)

$('img').each(function() { 
    if ($(this).attr("width") && $(this).attr("height")) {
      var scaledHeight = $(this).attr("height") * $(this).width() / $(this).attr("width");
      $(this).wrap('<span style="height: '+scaledHeight+'px; display:inline-block">');
    }
});
img {
  max-width: 100%;
  height: auto;
}

/* Just so you can see what it's doing: */
span {border:1px solid}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img src="http://placehold.it/2500x100" width="2500" height="100">
<img src="http://placehold.it/1000x300" width="1000" height="300">
<img src="http://placehold.it/100x100" width="100" height="100">
<img src="http://placehold.it/100x100">

关于javascript - 以不会导致浏览器因低速连接而回流的方式定义响应式图像(首选 HTML),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49361667/

相关文章:

javascript - 如何在 Javascript 中使用 for 调用动态命名方法

javascript - JS检测屏幕宽度,运行不同的JS文件

javascript - 下拉选择框选项在 chrome 浏览器中不起作用

html - 如何将 Div 放置在具有自动边距的容器外部并使其填充浏览器的其余宽度?

html - 我的 HTML/CSS 中禁用了滚动条?同时使用 Progid Microsoft 渐变。

css - mdbook中如何配置自定义字体,在生成的书籍中自动使用?

java - 通过 ajax 将数组传递给 servlet 给出 null 参数

javascript - 在 chrome 扩展程序中获取选定的文本

html - 如何集中div crossbrowser

css - 如何选择具有匹配类的表的最后一行?