import logo from './logo.svg';
import './App.css';
import React, { useLayoutEffect, useRef } from 'react';
function App() {
const ref = useRef()
const getStyle = () => {
let style = {}
const color = ['red', 'black', 'blue', 'yellow']
const maxIndex = Math.floor(Math.random() * 4)
style.background = color[maxIndex]
style.height = Math.floor(Math.random() * 50 + 100) + 'px'
return style
}
const setFlow = () => {
const children = ref.current.children
// document.querySelectorAll('.box')
console.log('children', children)
const height = [].map.call(children, (it) => it.offsetHeight)
var ccontent = children
var BoxHeightArr = []
const width = ccontent[0].offsetWidth
const num = document.documentElement.clientWidth /ccontent[0].offsetWidth
for(let i=0;i<ccontent.length;i++){
if(i<num){
BoxHeightArr[i] = ccontent[i].offsetHeight
}
else {
const minHeight = Math.min.apply(null,BoxHeightArr)
const minIndex = [].findIndex.call(BoxHeightArr,(val)=>val === minHeight)
ccontent[i].style.position='absolute'
ccontent[i].style.left = width * minIndex + 'px'
ccontent[i].style.top = minHeight + 'px'
BoxHeightArr[minIndex] = BoxHeightArr[minIndex] + ccontent[i].offsetHeight
}
}
console.log('height', height)
}
useLayoutEffect(() => {
setFlow()
})
return (
<div className='container' ref={ref}>
<div className='box' style={getStyle()}></div>
<div className='box' style={getStyle()}></div>
<div className='box' style={getStyle()}></div>
<div className='box' style={getStyle()}></div>
<div className='box' style={getStyle()}></div>
<div className='box' style={getStyle()}></div>
<div className='box' style={getStyle()}></div>
<div className='box' style={getStyle()}></div>
<div className='box' style={getStyle()}></div>
<div className='box' style={getStyle()}></div>
<div className='box' style={getStyle()}></div>
<div className='box' style={getStyle()}></div>
<div className='box' style={getStyle()}></div>
<div className='box' style={getStyle()}></div>
<div className='box' style={getStyle()}></div>
<div className='box' style={getStyle()}></div>
</div>
);
}
export default App;
实现瀑布流
最新推荐文章于 2024-07-08 16:22:29 发布