如何用JavaScript实现描述文本换行时自动隐藏尺寸文本?
自适应控制卡片底部尺寸文本的显示状态
当前使用Jinja2渲染的卡片底部结构中,当description-text内容过长时,会导致dimension-text跟着换行,破坏页面布局。需要实现:当描述文本与尺寸文本无法在同一行容纳时,隐藏尺寸文本;空间足够时重新显示。
实现思路
- 获取关键DOM元素:描述文本容器、描述文本、尺寸文本
- 编写判断逻辑:计算两个文本的总宽度(包含容器设置的间距),与容器可用宽度对比,判断是否能在一行容纳
- 绑定触发时机:页面加载完成后执行一次判断,同时监听窗口大小变化,实时调整显示状态
完整代码示例
原HTML结构(保留Jinja2模板)
<div class="card-footer d-flex justify-content-between"> <small class="me-2 d-flex gap-2 description-container"> <span id="description-text" class="description-text"> {% if photo.description %} {{ photo.description }} {% endif %} </span> <span id="dimension-text" class="dimension-text text-muted"> {% if photo.width and photo.height %} (Dimensions: {{ photo.width }} x {{ photo.height }}) {% endif %} </span> </small> <small class="float-end text-muted text-end"> {% if photo.category %} {{ photo.category }} {% endif %} </small> </div>
JavaScript实现代码
// 获取目标DOM元素 const descriptionContainer = document.querySelector('.description-container'); const descriptionText = document.getElementById('description-text'); const dimensionText = document.getElementById('dimension-text'); // 判断尺寸文本是否需要显示的核心函数 function toggleDimensionText() { // 元素不存在时直接返回,避免报错 if (!descriptionContainer || !descriptionText || !dimensionText) return; // 获取容器实际设置的间距值 const containerStyle = window.getComputedStyle(descriptionContainer); const gapValue = parseFloat(containerStyle.gap); // 计算两个文本需要的总宽度(含间距) const totalRequiredWidth = descriptionText.offsetWidth + dimensionText.offsetWidth + gapValue; // 获取容器的可用宽度 const containerAvailableWidth = descriptionContainer.offsetWidth; // 根据宽度对比结果控制显示/隐藏 dimensionText.style.display = totalRequiredWidth > containerAvailableWidth ? 'none' : 'inline'; } // 页面加载完成后执行一次判断 window.addEventListener('load', toggleDimensionText); // 窗口大小变化时实时调整 window.addEventListener('resize', toggleDimensionText);
说明
- 通过
getComputedStyle获取容器的实际间距,保证宽度计算的准确性 - 加入元素存在性判断,避免DOM元素未加载或不存在时抛出错误
- 监听
resize事件,确保窗口缩放时能实时适配布局
内容的提问来源于stack exchange,提问作者MyPing0
相关产品推荐
相关产品推荐

