如何在JavaScript中实现投票Div宽度变化的动画效果?
解决YES/NO投票图表宽度过渡动画不生效的问题
你的问题核心在于每次更新投票时,都销毁了原有DOM元素并重新创建新的.poll-attr节点——新元素直接被设置了最终宽度值,没有初始宽度作为过渡起点,因此CSS transition无法触发动画效果。
解决方案1:复用现有DOM元素(推荐)
不要每次清空容器重建元素,而是检查容器内是否已有投票元素,存在则直接更新其宽度和文本,这样元素有初始状态,修改宽度时自然触发过渡:
function renderPoll(){ // 查询容器内已有的投票元素 let poll1 = container.querySelector('.poll-attr:first-child'); let poll2 = container.querySelector('.poll-attr:last-child'); // 若元素不存在,再创建并添加到容器 if (!poll1 || !poll2) { poll1 = document.createElement('div'); poll2 = document.createElement('div'); poll1.classList.add('poll-attr'); poll2.classList.add('poll-attr'); container.appendChild(poll1); container.appendChild(poll2); } const yesPercent = calcPerc(); const roundedYes = Math.round(yesPercent); const noPercent = 100 - yesPercent; const roundedNo = 100 - roundedYes; // 更新宽度,此时元素有初始值,transition会生效 poll1.style.width = yesPercent + '%'; poll2.style.width = noPercent + '%'; poll1.innerText = roundedYes + '%'; poll2.innerText = roundedNo + '%'; }
解决方案2:强制触发重排(仅当必须重建元素时使用)
如果一定要清空重建元素,需要先给新元素设置初始宽度,强制浏览器完成重排后再设置目标宽度,让transition有过渡的起点和终点:
function renderPoll(){ container.innerHTML=''; // 清空容器 let poll1 = document.createElement('div'); let poll2 = document.createElement('div'); poll1.classList.add('poll-attr'); poll2.classList.add('poll-attr'); // 设置初始宽度(比如YES为0%,NO为100%) poll1.style.width = '0%'; poll2.style.width = '100%'; container.appendChild(poll1); container.appendChild(poll2); // 强制浏览器重排,固化初始状态 void container.offsetWidth; const yesPercent = calcPerc(); const roundedYes = Math.round(yesPercent); // 设置目标宽度,触发过渡动画 poll1.style.width = yesPercent + '%'; poll2.style.width = 100 - yesPercent + '%'; poll1.innerText = roundedYes + '%'; poll2.innerText = 100 - roundedYes + '%'; }
必须配置的CSS
确保.poll-attr类正确添加transition样式:
.poll-attr { /* 你的其他样式:height、background-color、display: inline-block等 */ transition: width 100ms linear; }
关键原理
CSS transition生效的前提是:元素的某个CSS属性从一个已存在的值平滑变化到另一个值。每次重建元素时,新元素直接被赋予最终宽度,没有过渡的起始状态,所以动画不会触发。复用元素或强制重排,都是为了给元素提供明确的初始状态,让浏览器能计算过渡动画。
内容的提问来源于stack exchange,提问作者Alex Dan
相关产品推荐
相关产品推荐

