Implementing the waterfall flow effect of images based on JavaScript
Waterfall flow layout is a common way to display images on a web page. It can make the images flow in a flowing way. display, giving people a unique visual effect. In this article, we will use JavaScript to implement a simple image waterfall effect.
<div id="gallery"></div>
#gallery { width: 1000px; column-count: 4; column-gap: 20px; } #gallery img { width: 100%; position: absolute; }
var container = document.getElementById('gallery'); var images = [ 'path_to_image1', 'path_to_image2', 'path_to_image3', // ... ];
Then, we need to create an array to save the height of each column.
var columnHeights = [];
Next, we can traverse all image resources, create an img element for each image, and add it to the container element. At the same time, we need to calculate where each image should be placed.
images.forEach(function(image) { // 创建 img 元素 var img = new Image(); img.src = image; // 计算图片应放置的位置 var columnIndex = 0; var minHeight = columnHeights[0]; for(var i = 1; i < columnHeights.length; i++) { if(columnHeights[i] < minHeight) { columnIndex = i; minHeight = columnHeights[i]; } } var left = columnIndex * (img.width + 20); var top = minHeight; // 设置图片位置 img.style.left = left + 'px'; img.style.top = top + 'px'; // 更新列高度 columnHeights[columnIndex] = top + img.height + 20; // 将图片添加到容器元素中 container.appendChild(img); });
图片瀑布流效果 <div id="gallery"></div> <script> var container = document.getElementById('gallery'); var images = [ 'path_to_image1', 'path_to_image2', 'path_to_image3', // ... ]; var columnHeights = []; images.forEach(function(image) { var img = new Image(); img.src = image; var columnIndex = 0; var minHeight = columnHeights[0]; for(var i = 1; i < columnHeights.length; i++) { if(columnHeights[i] < minHeight) { columnIndex = i; minHeight = columnHeights[i]; } } var left = columnIndex * (img.width + 20); var top = minHeight; img.style.left = left + 'px'; img.style.top = top + 'px'; columnHeights[columnIndex] = top + img.height + 20; container.appendChild(img); }); </script>
Through the above code, we successfully implemented a simple picture waterfall flow effect. In actual projects, more complex style modifications and interactive functions can be added to the waterfall flow layout according to needs.
The above is the detailed content of Implementing image waterfall flow effect based on JavaScript. For more information, please follow other related articles on the PHP Chinese website!