You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何检测flex-wrap容器内元素换行时刻及识别行末元素?

问题描述

我有一段React示例代码,实现了在设置flex-wrap: wrap的容器中,通过ref遍历元素并高亮当前元素。实际需求是始终仅显示三行文字,因此需要编写函数移除首行的N个元素,并同步更新索引与ref(需适配视口宽度);后续还要能添加元素到数组中。

要确定需移除的元素数量N,得识别出行末元素的索引,这样在点击按钮切换到行末元素时就能执行移除函数。我需要一种不依赖CSS属性取值的方案,来检测当前元素进入flex容器下一行的时刻,以及识别行末元素。此前尝试通过对比wrap_box_ref与current_word_ref的getBoundingClientRect().right值来判断行末,但该方法依赖justify-content属性取值,改成flex-start就失效了,现在寻求可行方案。

React组件代码
import { useState, useRef, useEffect, useCallback } from 'react'
import './App.css'

function Some_long_array(len: number) {
  let array = [];
  for (let i = 0; i < len; i++) array.push('array');
  return array;
}

function App() {
  const [array, Set_array] = useState(() => Some_long_array(50));
  const wrap_box_ref = useRef<HTMLDivElement>(null)
  const current_word_ref = useRef<Element | null>(null);
  const current_word_index = useRef(0);

  const Handle_advance = useCallback(() => {
    if (current_word_index.current + 1 >= array.length) return;
    current_word_ref.current!.classList.remove('some_class');
    current_word_index.current++;
    current_word_ref.current = wrap_box_ref.current!.children[current_word_index.current]
    current_word_ref.current.classList.add('some_class');
  }, [array]);

  useEffect(() => {
    if (!wrap_box_ref.current) return;
    current_word_ref.current = wrap_box_ref.current.children[current_word_index.current];
    current_word_ref.current.classList.add('some_class');
  }, []) 

  return (
    <>
      <div id='wrap_box' ref={wrap_box_ref}>
        {
          array.map((el, index) => 
            <div className='word' key={el + index.toString()}>
              {el}
            </div>
          )
        }
      </div>
      <button style={{padding: 10}} onClick={Handle_advance}>
        Click me to advance to next word!
      </button>
    </>
  )
}

export default App
CSS样式
*{
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}
#wrap_box{
  display: flex;
  align-items: center;
  justify-content: space-between; /* 此处可能改为'flex-start' */
  flex-wrap: wrap;
  gap: 10px;
  font-size: 2em;
}
.word{
  display: inline;
}
.some_class{
  background-color: pink;
}

内容的提问来源于stack exchange,提问作者Andrey Dorofeev

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.16 08:55:08