<! DOCTYPE html >
< html lang = " en" > < head> < meta charset = " UTF-8" /> < meta name = " viewport" content = " width=device-width, initial-scale=1.0" /> < title> 11.瀑布流布局</ title> < style> #container { position : relative; } img { position : absolute; } </ style> </ head> < body> < div id = " container" > </ div> </ body> < script> var divContainer = document. getElementById ( 'container' ) var imgWidth = 220 function createImgs ( ) { for ( var i = 0 ; i <= 40 ; i++ ) { var height = Math. ceil ( Math. random ( ) * 100 + 200 ) var src = 'https://picsum.photos/220/' + height var img = document. createElement ( 'img' ) img. onload = setPoisionsimg. src = src divContainer. appendChild ( img) } } createImgs ( ) function setPoisions ( ) { function cal ( ) { var containerWidth = divContainer. clientWidth var columns = Math. floor ( containerWidth / imgWidth) var spaceNumber = columns + 1 var leftSpace = containerWidth - columns * imgWidth var space = leftSpace / spaceNumber return { space : space, columns : columns, } } var info = cal ( ) var nextTops = new Array ( info. columns) nextTops. fill ( 0 ) for ( var i = 0 ; i < divContainer. children. length; i++ ) { var img = divContainer. children[ i] var minTop = Math. min . apply ( null , nextTops) img. style. top = minTop + 'px' var index = nextTops. indexOf ( minTop) nextTops[ index] += img. height + info. spacevar left = ( index + 1 ) * info. space + index * imgWidthimg. style. left = left + 'px' } var max = Math. max . apply ( null , nextTops) divContainer. style. height = max + 'px' } var timerId = null window. onresize = function ( ) { if ( timerId) { clearTimeout ( timerId) } timerId = setTimeout ( setPoisions, 300 ) } </ script>
</ html>