search
HomeWeb Front-endHTML Tutorial瀑布流代码实现(绝对定位)_html/css_WEB-ITnose

瀑布流是页面展示中十分常见的一种布局方式,利用这种布局,网页会显得十分好看。瀑布流元素最大的特点是等宽不等高,下面我一步步来分析如何实现瀑布流。

1.首先,我们准备一些图片,以及把基础的html+css代码写好(因为这步很简单,所以我就直接贴代码了)。

  • 页面初始效果

pic1.png

  • 网页结构
    <!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>瀑布流</title><link rel="stylesheet" href="index.css"></head><body><div class="container">    <div class="box">        <div class="box-img">            <img src="/static/imghwm/default1.png"  data-src="img1.jpg"  class="lazy" alt="pic1">        </div>    </div>    <div class="box">        <div class="box-img">            <img src="/static/imghwm/default1.png"  data-src="img2.jpg"  class="lazy" alt="pic2">        </div>    </div>    <div class="box">        <div class="box-img">            <img src="/static/imghwm/default1.png"  data-src="img3.jpg"  class="lazy" alt="pic3">        </div>    </div>    <div class="box">        <div class="box-img">            <img src="/static/imghwm/default1.png"  data-src="img4.jpg"  class="lazy" alt="pic4">        </div>    </div>    <div class="box">        <div class="box-img">            <img src="/static/imghwm/default1.png"  data-src="img5.jpg"  class="lazy" alt="pic5">        </div>    </div>    <div class="box">        <div class="box-img">            <img src="/static/imghwm/default1.png"  data-src="img6.jpg"  class="lazy" alt="pic6">        </div>    </div></div></body></html>
  • css
    *{margin: 0;padding: 0;}.container{position: relative;width: 1040px;margin: 0 auto;}.box{float: left;padding: 5px;font-size: 0;}.box-img img{width: 250px;}

2.实现瀑布流效果

原理:1.根据所设的宽度,获得每一行可以放几列(我的列子中是写死的,一行放4列);2.获取每个元素的高度,保存在数组中;3.从第一个元素依次设置每个元素的定位:   3.1 先获得这个元素该放在第几列(现有高度最小的列),通过下面的getMinHeightCol函数;   3.2 根据每列的宽以及每列的当前高度,设置元素的left,top值(当然也要设置position:absolute);   3.3 重新修改每列的当前高度(为了3.1获得最新的“高度最小的列”);
  • js代码(依赖jquery)
$(function(){    var elesHeight = [];//每个元素的宽度    var colsHeight = [0,0,0,0]; //每列元素现有的高度    $(".container .box").each(function(index,item){        var eleHeight = $(this).height();        elesHeight.push(eleHeight);    });    //依次摆放每一个元素    $(".container .box").each(function(index,item){        //获得该元素应该在第几列        var colShould = getMinHeightCol(colsHeight);        var tempTop = colsHeight[colShould];        var tempLeft = colShould*260;        $(this).css({"position":"absolute","top":tempTop+"px",left:tempLeft+"px"});        //同时将该列的高度加上当前新增元素的高度        colsHeight[colShould] += $(this).height();    });    //得到四列中高度最小的那一列    function getMinHeightCol(arr){        var minHeight = Math.min.apply(null, arr);        console.log("最小高度:"+minHeight);        for(var i in arr){            if(arr[i]==minHeight){                return i;            }        }        //默认第一列        return 0;    }});
  • 页面效果

pic2.png

上面只是简单的瀑布流实现,一个完整的瀑布流应该也具备下面的几个特点:

  • 列数根据页面宽度和每列的宽度自动计算得来;
  • 窗口大小改变时,重新计算元素布局的位置;
  • 解决——窗口大小快速变化时,会不断地触发事件,造成的大量的性能消耗。
    针对第三个问题的setTimeout解决方法:窗口变化之后开始计时,如果窗口还在变换则从新开始计时,窗口不再变化则延时(很短的时间)触发重排事件。var re;window.onresize = function() {  clearTimeout(re);  re = setTimeout(resize,100); };

剩余的优化,自己动手尝试吧~

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Why are HTML attributes important for web development?Why are HTML attributes important for web development?May 12, 2025 am 12:01 AM

HTMLattributesarecrucialinwebdevelopmentforcontrollingbehavior,appearance,andfunctionality.Theyenhanceinteractivity,accessibility,andSEO.Forexample,thesrcattributeintagsimpactsSEO,whileonclickintagsaddsinteractivity.Touseattributeseffectively:1)Usese

What is the purpose of the alt attribute? Why is it important?What is the purpose of the alt attribute? Why is it important?May 11, 2025 am 12:01 AM

The alt attribute is an important part of the tag in HTML and is used to provide alternative text for images. 1. When the image cannot be loaded, the text in the alt attribute will be displayed to improve the user experience. 2. Screen readers use the alt attribute to help visually impaired users understand the content of the picture. 3. Search engines index text in the alt attribute to improve the SEO ranking of web pages.

HTML, CSS, and JavaScript: Examples and Practical ApplicationsHTML, CSS, and JavaScript: Examples and Practical ApplicationsMay 09, 2025 am 12:01 AM

The roles of HTML, CSS and JavaScript in web development are: 1. HTML is used to build web page structure; 2. CSS is used to beautify the appearance of web pages; 3. JavaScript is used to achieve dynamic interaction. Through tags, styles and scripts, these three together build the core functions of modern web pages.

How do you set the lang attribute on the  tag? Why is this important?How do you set the lang attribute on the tag? Why is this important?May 08, 2025 am 12:03 AM

Setting the lang attributes of a tag is a key step in optimizing web accessibility and SEO. 1) Set the lang attribute in the tag, such as. 2) In multilingual content, set lang attributes for different language parts, such as. 3) Use language codes that comply with ISO639-1 standards, such as "en", "fr", "zh", etc. Correctly setting the lang attribute can improve the accessibility of web pages and search engine rankings.

What is the purpose of HTML attributes?What is the purpose of HTML attributes?May 07, 2025 am 12:01 AM

HTMLattributesareessentialforenhancingwebelements'functionalityandappearance.Theyaddinformationtodefinebehavior,appearance,andinteraction,makingwebsitesinteractive,responsive,andvisuallyappealing.Attributeslikesrc,href,class,type,anddisabledtransform

How do you create a list in HTML?How do you create a list in HTML?May 06, 2025 am 12:01 AM

TocreatealistinHTML,useforunorderedlistsandfororderedlists:1)Forunorderedlists,wrapitemsinanduseforeachitem,renderingasabulletedlist.2)Fororderedlists,useandfornumberedlists,customizablewiththetypeattributefordifferentnumberingstyles.

HTML in Action: Examples of Website StructureHTML in Action: Examples of Website StructureMay 05, 2025 am 12:03 AM

HTML is used to build websites with clear structure. 1) Use tags such as, and define the website structure. 2) Examples show the structure of blogs and e-commerce websites. 3) Avoid common mistakes such as incorrect label nesting. 4) Optimize performance by reducing HTTP requests and using semantic tags.

How do you insert an image into an HTML page?How do you insert an image into an HTML page?May 04, 2025 am 12:02 AM

ToinsertanimageintoanHTMLpage,usethetagwithsrcandaltattributes.1)UsealttextforaccessibilityandSEO.2)Implementsrcsetforresponsiveimages.3)Applylazyloadingwithloading="lazy"tooptimizeperformance.4)OptimizeimagesusingtoolslikeImageOptimtoreduc

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version