search
HomeWeb Front-endHTML Tutorial瀑布流!而且还是响应式的哦!_html/css_WEB-ITnose

Untitled.gif

没错!这就是瀑布流!是不是很酷炫!看似很难实现,实则很简单!我是用li标签创建这些小块块,当然你也可以根据你的需要在li标签里,插入图片或者其他.下面我们就学习一下,如何实现网页的响应式瀑布流!

第一步编写HTML

可能会有小伙伴认为我们有20个块,需要写20个标签,那你就错了,在JS代码中我们可以利用for循环在HTML中查入10个.100个.1000个你想有多少就有多少!当然你最好提前为你的瀑布流做好css样式,我的这些小块都是由li标签创建的,这样在JS中创造的li标签直接赋予相应的类名.

<!DOCTYPE html><html>    <head>        <meta charset="UTF-8">        <title></title>        <style type="text/css">            * {                margin: 0;                padding: 0;            }            #flow {                list-style: none;                margin: 0 auto;                position: relative;            }            #flow li {                position: absolute;                background-color: #CCCCCC;                font-size: 50px;                width: 200px;                transition: all 0.5s;            }        </style>    </head>    <body>        <ul id="flow">            <!--<li>1</li>-->        </ul>    </body>

第二步 JS代码准备工作

这步中我们需要创建一个随机数,其函数的返回值我们用来定义每一个li元素的高度,当然如果你不想随机定义高度,那你就去写个数组吧!因为我的整体布局距离左边有10px距离,所以此处创建了一个leftSpace变量接受了一下.细心朋友可能已经发现了我的每一个元素期间都有10px的间距,所以此处创建了一个paddingSpace变量来限定每个li元素的间距.其他的在代码中都有相应的注释,自行理解!

<script type="text/javascript">        function ranH (min,max) {            return parseInt(Math.random()*(max-min+1))+min;        }        var flow = document.getElementById("flow");        // 左边距        var leftSpace = 10;        // 间距        var paddingSpace = 10;        //高度数组 保存每个li的高度        var hs = [];

第三步 创建li元素

由于在这步代码中,我们会看到出现bol值,而我们是在第四步定义了bol的值,并且根据bol的值来确定layout函数是实现创建li,还是更新li的位置.在这步我们可以先认为bol为true.首先,是创建li标签,然后获取屏幕的宽度根据屏幕的宽度设置一行有几个li标签,再根据li的标签的个数定义ul的宽度.在定义一下每列的li元素的高度,此处的作用是为了第四步的选出最短列而做准备.在给予每个li标签HTML内容,并且保存每个li的高度.

        //布局函数        //bol为真时 创建li        //bol为假时 更新li位置        function layout (bol) {            //获取所有的li 用于大小改变时 更新布局            var lis = document.getElementsByTagName("li");            var cols = parseInt(document.documentElement.clientWidth/200);                //ul宽度 跟随宽度一起变化            flow.style.width = cols*200 + 10*(cols-1)+20;            //初始化列高数组            var arrH =[];            for (var i = 0; i < cols; i++) {                arrH[i]=10;            }            function createLi (index) {                //获取已有的li或者新建                var li = lis[index]||document.createElement("li");                li.innerHTML = index;                //从数组中获取高度或者随机高度                var h = hs[index]||ranH(100,300);                li.style.height = h+"px";                if (bol) {                    hs.push(h);                }

第四步 插入创建好的带有内容li标签.并且与第三步呼应,实现响应式瀑布流.

首先求出最短列,将li元素插入最短列下,定义每一个li的位置.在最后利用系统的window.onresize 函数,当屏幕尺寸改变时执行layout()方法中,更新li位置的方法,以实现响应式瀑布流!

//求最短列                var minH = arrH[0];                var minI = 0;                for (var i = 0; i < cols; i++) {                    if (minH>arrH[i]) {                        minH=arrH[i];                        minI=i;                    }                }                //设置left                var  l = leftSpace+(200+paddingSpace)*minI;                li.style.left = l+"px";                //设置top                li.style.top = arrH[minI]+"px";                //添加                bol&&flow.appendChild(li);//                alert(li.offsetLeft+"~"+li.offsetTop+"~"+li.offsetWidth+"~"+li.offsetHeight);                //更新高度                arrH[minI] = arrH[minI] + li.offsetHeight +paddingSpace;            }            for (var i =0 ; i < 20 ;i++) {                createLi(i);            }        }        //创建        layout(true);        window.onresize =function  () {            //更新            layout(false);        }    </script></html>
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
What are boolean attributes in HTML? Give some examples.What are boolean attributes in HTML? Give some examples.Apr 25, 2025 am 12:01 AM

Boolean attributes are special attributes in HTML that are activated without a value. 1. The Boolean attribute controls the behavior of the element by whether it exists or not, such as disabled disable the input box. 2.Their working principle is to change element behavior according to the existence of attributes when the browser parses. 3. The basic usage is to directly add attributes, and the advanced usage can be dynamically controlled through JavaScript. 4. Common mistakes are mistakenly thinking that values ​​need to be set, and the correct writing method should be concise. 5. The best practice is to keep the code concise and use Boolean properties reasonably to optimize web page performance and user experience.

How can you validate your HTML code?How can you validate your HTML code?Apr 24, 2025 am 12:04 AM

HTML code can be cleaner with online validators, integrated tools and automated processes. 1) Use W3CMarkupValidationService to verify HTML code online. 2) Install and configure HTMLHint extension in VisualStudioCode for real-time verification. 3) Use HTMLTidy to automatically verify and clean HTML files in the construction process.

HTML vs. CSS and JavaScript: Comparing Web TechnologiesHTML vs. CSS and JavaScript: Comparing Web TechnologiesApr 23, 2025 am 12:05 AM

HTML, CSS and JavaScript are the core technologies for building modern web pages: 1. HTML defines the web page structure, 2. CSS is responsible for the appearance of the web page, 3. JavaScript provides web page dynamics and interactivity, and they work together to create a website with a good user experience.

HTML as a Markup Language: Its Function and PurposeHTML as a Markup Language: Its Function and PurposeApr 22, 2025 am 12:02 AM

The function of HTML is to define the structure and content of a web page, and its purpose is to provide a standardized way to display information. 1) HTML organizes various parts of the web page through tags and attributes, such as titles and paragraphs. 2) It supports the separation of content and performance and improves maintenance efficiency. 3) HTML is extensible, allowing custom tags to enhance SEO.

The Future of HTML, CSS, and JavaScript: Web Development TrendsThe Future of HTML, CSS, and JavaScript: Web Development TrendsApr 19, 2025 am 12:02 AM

The future trends of HTML are semantics and web components, the future trends of CSS are CSS-in-JS and CSSHoudini, and the future trends of JavaScript are WebAssembly and Serverless. 1. HTML semantics improve accessibility and SEO effects, and Web components improve development efficiency, but attention should be paid to browser compatibility. 2. CSS-in-JS enhances style management flexibility but may increase file size. CSSHoudini allows direct operation of CSS rendering. 3.WebAssembly optimizes browser application performance but has a steep learning curve, and Serverless simplifies development but requires optimization of cold start problems.

HTML: The Structure, CSS: The Style, JavaScript: The BehaviorHTML: The Structure, CSS: The Style, JavaScript: The BehaviorApr 18, 2025 am 12:09 AM

The roles of HTML, CSS and JavaScript in web development are: 1. HTML defines the web page structure, 2. CSS controls the web page style, and 3. JavaScript adds dynamic behavior. Together, they build the framework, aesthetics and interactivity of modern websites.

The Future of HTML: Evolution and Trends in Web DesignThe Future of HTML: Evolution and Trends in Web DesignApr 17, 2025 am 12:12 AM

The future of HTML is full of infinite possibilities. 1) New features and standards will include more semantic tags and the popularity of WebComponents. 2) The web design trend will continue to develop towards responsive and accessible design. 3) Performance optimization will improve the user experience through responsive image loading and lazy loading technologies.

HTML vs. CSS vs. JavaScript: A Comparative OverviewHTML vs. CSS vs. JavaScript: A Comparative OverviewApr 16, 2025 am 12:04 AM

The roles of HTML, CSS and JavaScript in web development are: HTML is responsible for content structure, CSS is responsible for style, and JavaScript is responsible for dynamic behavior. 1. HTML defines the web page structure and content through tags to ensure semantics. 2. CSS controls the web page style through selectors and attributes to make it beautiful and easy to read. 3. JavaScript controls web page behavior through scripts to achieve dynamic and interactive functions.

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 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.

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)