点击表格行触发CSS transition仅首次生效问题求解
问题原因
- 内联样式优先级高于类选择器优先级:第一次点击后你给
derDiv设置了top: 0的内联样式,后续添加的.auxClas里的top: -400px不会生效,top属性一直保持为0,没有数值变化自然不会触发过渡。 - 样式修改被浏览器合并渲染:即使你能把top改回-400px,如果没有触发浏览器重排就直接改回0,浏览器会合并两次样式修改,也看不到过渡效果。
- 代码冗余:
.auxClas和.der的样式完全重复,属于无效代码。
修复方案
1. 简化CSS
删掉冗余的.auxClas相关样式即可,保留原.der的样式:
#container { width: 80%; display: flex; margin: 0 auto; justify-content: space-between; } .izq { flex-basis: 40%; } .der { flex-basis: 40%; display: flex; flex-direction: column; position: relative; top: -400px; transition: top 1s; } .info { flex-basis: 30%; } .info img { width: 100%; }
2. 修改JS逻辑
去掉冗余的cont计数,每次点击先重置状态、触发重排后再赋值触发过渡:
let table = document.querySelectorAll(".table-row"); let derDiv = document.querySelector(".der"); let derInfoDiv = document.querySelector(".der .info"); table.forEach(tr => { tr.addEventListener('click', () => { // 清空现有内容 derInfoDiv.innerHTML = ''; // 清空derDiv里除了.info之外的元素(也就是之前添加的h3) Array.from(derDiv.children).forEach(child => { if (!child.classList.contains('info')) child.remove(); }); // 重置top到初始位置 derDiv.style.top = '-400px'; // 强制触发浏览器重排,让上面的重置生效,不会和后面的赋值合并 void derDiv.offsetHeight; // 添加新内容 let title = tr.children[0].textContent; let imgSrc = tr.children[1].children[0].src; const img = document.createElement("img"); img.src = imgSrc; const h3 = document.createElement("h3"); h3.textContent = title; derDiv.appendChild(h3); derInfoDiv.appendChild(img); // 触发过渡 derDiv.style.top = 0; }) });
HTML部分无需修改。
内容的提问来源于stack exchange,提问作者DarkVaderM
相关产品推荐
相关产品推荐

