JavaScript 如何实现横向瀑布流

 5908

最近在做一个小程序项目,在 UI 上借鉴了一下其他 App 设计,其中有一个图片横向布局铺满的 UI 感觉挺好看的,类似于传统的瀑布流布局横过来一样。于是就自己实现了一下,并且将原本的横向两张图的方法扩展了下,改成了可以自定义显示张数的方法。下面是基本的显示效果:


5ec6038bdd092.jpg

5ec603a66e078.jpg


下面先说说写这个方法时的思路:

效果分析

可以看到在上图中,单行不管显示几张图片,都几乎能够保证图片被完整显示出来,并且每一行的高度都不同——这是为了保证每张图都能几乎完整显示,所以必须要根据实际要显示的图片来动态地调整行高。

由于像素渲染必须取整,所以计算图片的宽高方面会存在 1~2px 的误差。这个误差可以直接忽略,并不会导致图片在视觉上产生拉伸。

分析完效果后,就有了下面几个问题:

1、如何保证每一行都能完整显示里面的图片?要知道每张图片的宽高都是不同的

2、如何动态计算每一行的高度?

3、在最后图片剩余数量不满足单行显示的图片数的情况下,如何对最后一行的图片进行布局?

4、……

问题分析

先来看第一个问题:如何保证单行的每一张图片都能完整显示。

首先我们可以确定单行的图片显示数量,这个是预先设置好的,比如上面的单行 5 张图 numberInLine = 5。而同一行中的每张图片高度都相同,这样就可以根据图片宽度与所有图片的总宽度的比值,计算出这张图片实际渲染时占单行的宽度,公式如下:

imageRenderWidth = (imageWidth / imagesTotalWidth) * lineWidth

虽然图片的实际宽高各不相同,但是由于单行图片的高度都相同,我们就可以通过先假设一个标准高度 stdHeight ,通过这个标准高度把每张图片的宽度都进行比例缩放,这样就可以顺利计算出单张图片宽度在所有图片总宽度中的比值

如何计算每一行的高度

在能够确定图片宽度的前提下,要确定每一行的高度相对就非常简单了。以每行第一张图片为基准,先计算出第一张图片的渲染宽度,然后计算出这张图片的渲染高度,并以此作为行高,之后的每张图片都通过行高计算出各自的渲染宽度。但是需要注意的是,为了填满单行,最后一张图片需要通过总宽度-之前所有图片宽度之和的方式计算出,否则就会有空白,表达公式如下:

  1. // 第一张图片渲染宽度
  2. firstImageRenderWidth = (firstImageWidth / imagesTotalWidth) * lineWidth
  3. // 第一张图片渲染高度,即行高,即该行所有图片高度
  4. lineHeight = imagesRenderHeight = firstImageRenderWidth / (firstImageWidth / firstImageHeight)
  5. // 中间图片渲染宽度
  6. middleImageRenderWidth = lineHeight * (middleImageWidth / middleImageHeight)
  7. // 最后一张图片渲染宽度
  8. lastImageRenderWidth = lineWidth - otherImagesTotalRenderWidth

当剩余图片数量不足单行数量时如何布局?

这个问题需要分两种情况来考虑:

1、当单行需要 5 张,而剩余数量不足 5 张但大于 1 张时(如 4 张图片):该行可按照剩余图片的数量布局,算法依然如上。所以对于这点,需要让代码具有可复用性;

2、只剩下 1 张图片时,有下面几种处理方法:

可以将这张图片占满全部行宽并且完整显示,但是如果这张图片是高度很高的图片,就会严重影响布局的美观性

依然将图片占满行宽,但是给定一个最大高度,当高度不及最大高度时完整显示,当超过时只显示部分,这样能保证布局美观性,但是最后一张图片的显示存在瑕疵

取前一行的行高作为最后一行的行高,这样可以在保证整体布局一致性的情况下,依然可以完整显示图片,但是这样做最后一行会留有大量空白位置

对于上面三种处理方式,作者采用的是第二种。感兴趣的小伙伴可以自己尝试其他两种方式。或者如果你有更好的布局方式,也可以在评论里告诉作者哦!

不知道上面三个问题的解释小伙伴们有没有理解了呢?不理解也没事,可以直接通过代码来了解是如何解决这些问题的。

代码实现

  1. /* imagesLayout.js */
  2. /*
  3.  * 图片横向瀑布流布局 最大限度保证每张图片完整显示 可以获取最后计算出来的图片布局宽高信息 最后的瀑布流效果需要配合 css 实现(作者通过浮动布局实现)当然你也可以对代码进行修改 让其能够直接返回一段已经布局完成的 html 结构
  4.  * 需要先提供每张图片的宽高 如果没有图片的宽高数据 则可以在代码中添加处理方法从而获取到图片宽高数据后再布局 但是并不推荐这样做
  5.  * 尽量保证图片总数能被单行显示的数量整除 避免最后一行单张显示 否则会影响美观
  6.  * 每张图由于宽高取整返回的宽高存在0-2px的误差 可以通过 css 保证视觉效果
  7.  */
  8. /*
  9.  * @param images {Object} 图片对象列表,每一个对象有 src width height 三个属性
  10.  * @param containerWidth {Integer} 容器宽度
  11.  * @param numberInLine {Integer} 单行显示图片数量
  12.  * @param limit {Integer} 限制需要进行布局的图片的数量 如果传入的图片列表有100张 但只需要对前20张进行布局 后面的图片忽略 则可以使用此参数限制 如果不传则默认0(不限制)
  13.  * @param stdRatio {Float} 图片标准宽高比
  14.  */
  15. class ImagesLayout {
  16.     constructor(images, containerWidth, numberInLine = 10, limit = 0, stdRatio = 1.5) {
  17.         // 图片列表
  18.         this.images = images
  19.         // 布局完毕的图片列表 通过该属性可以获得图片布局的宽高信息
  20.         this.completedImages = []
  21.         // 容器宽度
  22.         this.containerWidth = containerWidth
  23.         // 单行显示的图片数量
  24.         this.numberInLine = numberInLine
  25.         // 限制布局的数量 如果传入的图片列表有100张 但只需要对前20张进行布局 后面的图片忽略 则可以使用此参数限制 如果不传则默认0(不限制)
  26.         this.limit = limit
  27.         // 图片标准宽高比(当最后一行只剩一张图片时 为了不让布局看上去很奇怪 所以要有一个标准宽高比 当图片实际宽高比大于标准宽高比时会发生截取 小于时按照实际高度占满整行显示)
  28.         this.stdRatio = stdRatio
  29.         // 图片撑满整行时的标准高度
  30.         this.stdHeight = this.containerWidth / this.stdRatio
  31.         this.chunkAndLayout()
  32.     }
  33.     // 将图片列表根据单行数量分块并开始计算布局
  34.     chunkAndLayout () {
  35.         // 当图片只有一张时,完整显示这张图片
  36.         if (this.images.length === 1) {
  37.             this.layoutFullImage(this.images[0])
  38.             return
  39.         }
  40.         let temp = []
  41.         for (let i = 0; i < this.images.length; i++) {
  42.             if (this.limit && i >= this.limit) return
  43.             temp.push(this.images[i])
  44.             // 当单行图片数量达到限制数量时
  45.             // 当已经是最后一张图片时
  46.             // 当已经达到需要布局的最大数量时
  47.             if (% this.numberInLine === this.numberInLine - 1 || i === this.images.length - 1 || i === this.limit - 1) {
  48.                 this.computedImagesLayout(temp)
  49.                 temp = []
  50.             }
  51.         }
  52.     }
  53.     // 完整显示图片
  54.     layoutFullImage (image) {
  55.         let ratio = image.width / image.height
  56.         image.width = this.containerWidth
  57.         image.height = parseInt(this.containerWidth / ratio)
  58.         this.completedImages.push(image)
  59.     }
  60.     // 根据分块计算图片布局信息
  61.     computedImagesLayout(images) {
  62.         if (images.length === 1) {
  63.             // 当前分组只有一张图片时
  64.             this.layoutWithSingleImage(images[0])
  65.         } else {
  66.             // 当前分组有多张图片时
  67.             this.layoutWithMultipleImages(images)
  68.         }
  69.     }
  70.     // 分组中只有一张图片 该张图片会单独占满整行的布局 如果图片高度过大则以标准宽高比为标准 其余部分剪裁 否则完整显示
  71.     layoutWithSingleImage (image) {
  72.         let ratio = image.width / image.height
  73.         image.width = this.containerWidth
  74.         // 如果是长图,则布局时按照标准宽高比显示中间部分
  75.         if (ratio < this.stdRatio) {
  76.             image.height = parseInt(this.stdHeight)
  77.         } else {
  78.             image.height = parseInt(this.containerWidth / ratio)
  79.         }
  80.         this.completedImages.push(image)
  81.     }
  82.     // 分组中有多张图片时的布局
  83.     // 以相对图宽为标准,根据每张图的相对宽度计算占据容器的宽度
  84.     layoutWithMultipleImages(images) {
  85.         let widths = [] // 保存每张图的相对宽度
  86.         let ratios = [] // 保存每张图的宽高比
  87.         images.forEach(item => {
  88.             // 计算每张图的宽高比
  89.             let ratio = item.width / item.height
  90.             // 根据标准高度计算相对图宽
  91.             let relateWidth = this.stdHeight * ratio
  92.             widths.push(relateWidth)
  93.             ratios.push(ratio)
  94.         })
  95.         // 计算每张图片相对宽度的总和
  96.         let totalWidth = widths.reduce((sum, item) => sum + item, 0)
  97.         let lineHeight = 0 // 行高
  98.         let leftWidth = this.containerWidth // 容器剩余宽度 还未开始布局时的剩余宽度等于容器宽度
  99.         images.forEach((item, i) => {
  100.             if (=== 0) {
  101.                 // 第一张图片
  102.                 // 通过图片相对宽度与相对总宽度的比值计算出在容器中占据的宽度与高度
  103.                 item.width = parseInt(this.containerWidth * (widths[i] / totalWidth))
  104.                 item.height = lineHeight = parseInt(item.width / ratios[i])
  105.                 // 第一张图片布局后的剩余容器宽度
  106.                 leftWidth = leftWidth - item.width
  107.             } else if (=== images.length - 1) {
  108.                 // 最后一张图片
  109.                 // 宽度为剩余容器宽度
  110.                 item.width = leftWidth
  111.                 item.height = lineHeight
  112.             } else {
  113.                 // 中间图片
  114.                 // 以行高为标准 计算出图片在容器中的宽度
  115.                 item.height = lineHeight
  116.                 item.width = parseInt(item.height * ratios[i])
  117.                 // 图片布局后剩余的容器宽度
  118.                 leftWidth = leftWidth - item.width
  119.             }
  120.             this.completedImages.push(item)
  121.         })
  122.     }
  123. }
  1. <!-- imagesLayout.html -->
  2. <!-- css 布局通过浮动实现 -->
  3. <style>
  4. * {
  5.   box-sizing: border-box;
  6. }
  7. #horizontal-waterfull {
  8.   width: 300px;
  9. }
  10. #horizontal-waterfull:before, #horizontal-waterfull:after {
  11.   content: '';
  12.   display: table;
  13.   clear: both;
  14. }
  15. img {
  16.   display: block;
  17.   width: 100%;
  18.   height: 100%;
  19. }
  20. .image-box {
  21.   float: left;
  22.   padding: 1px;
  23.   overflow: hidden;
  24. }
  25. </style>
  26. <div id="horizontal-waterfull"></div>
  27. <script src="./imagesLayout.js"></script>
  28. <script>
  29. // 待布局图片列表
  30. const images = [{
  31.     src: 'https://static.cxstore.top/images/lake.jpg',
  32.     width: 4000,
  33.     height: 6000
  34. }, {
  35.     src: 'https://static.cxstore.top/images/japan.jpg',
  36.     width: 1500,
  37.     height: 1125
  38. }, {
  39.     src: 'https://static.cxstore.top/images/girl.jpg',
  40.     width: 5616,
  41.     height: 3266
  42. }, {
  43.     src: 'https://static.cxstore.top/images/flower.jpg',
  44.     width: 4864,
  45.     height: 3648
  46. }, {
  47.     src: 'https://static.cxstore.top/images/lake.jpg',
  48.     width: 4000,
  49.     height: 6000
  50. }, {
  51.     src: 'https://static.cxstore.top/images/japan.jpg',
  52.     width: 1500,
  53.     height: 1125
  54. }, {
  55.     src: 'https://static.cxstore.top/images/grass.jpg',
  56.     width: 5184,
  57.     height: 2916
  58. }]
  59. // 获取布局容器
  60. const $box = document.getElementById('horizontal-waterfull')
  61. // 创建一个布局实例
  62. const layout = new ImagesLayout(images, $box.clientWidth, 4)
  63. // 通过 layout 的 completedImages 获取所有图片的布局信息
  64. layout.completedImages.forEach(item => {
  65.     let $imageBox = document.createElement('div')
  66.     $imageBox.setAttribute('class', 'image-box')
  67.     $imageBox.style.width = item.width + 'px'
  68.     $imageBox.style.height = item.height + 'px'
  69.     let $image = document.createElement('img')
  70.     $image.setAttribute('src', item.src)
  71.     $imageBox.appendChild($image)
  72.     $box.appendChild($imageBox)
  73. })


本文网址:https://www.zztuku.com/index.php/detail-7785.html
站长图库 - JavaScript 如何实现横向瀑布流
申明:如有侵犯,请 联系我们 删除。

评论(0)条

您还没有登录,请 登录 后发表评论!

提示:请勿发布广告垃圾评论,否则封号处理!!

    编辑推荐