2017-10-09 39 views
1

以下是使用left属性向右移动框的简单设置。该属性通过点击按钮进行更新。为什么在第一次点击按钮时不会应用过渡动画?为什么第一次设置属性时不应用动画(转换)

document.addEventListener('DOMContentLoaded',() => { 
 
    const box = document.querySelector('.box'); 
 
    const button = document.querySelector('button'); 
 
    button.addEventListener('click',() => { 
 
    const current = parseInt(box.style.left); 
 
    box.style.left = (isNaN(current) ? 0 : current) + 50 + "px"; 
 
    }); 
 
})
.box { 
 
    width: 100px; 
 
    height: 100px; 
 
    background: green; 
 
    position: relative; 
 
    transition: left 1s; 
 
}
<button>Click me!</button> 
 
<div class="box"></div>

回答

5

left初始值是autoauto不是可转换值。

您需要明确设置left: 0才能进行转换。

+0

很好,谢谢'auto'不是任何财产可转换值,是否正确? –

2

left的一些初始值开始。

document.addEventListener('DOMContentLoaded',() => { 
 
    const box = document.querySelector('.box'); 
 
    const button = document.querySelector('button'); 
 
    button.addEventListener('click',() => { 
 
     const current = parseInt(box.style.left); 
 
     box.style.left = (isNaN(current) ? 0 : current) + 50 + "px"; 
 
    }); 
 
})
.box { 
 
      left: 0; 
 
      width: 100px; 
 
      height: 100px; 
 
      background: green; 
 
      position: relative; 
 
      transition: left 1s; 
 
     }
<button>Click me!</button> 
 
<div class="box"></div>

1

“左” 属性intialized为 “自动”,没有过渡可以应用。 相反试试这个:

document.addEventListener('DOMContentLoaded',() => { 
 
    const box = document.querySelector('.box'); 
 
    const button = document.querySelector('button'); 
 
    button.addEventListener('click',() => { 
 
     const current = parseInt(box.style.left); 
 
     box.style.left = (isNaN(current) ? 0 : current) + 50 + "px"; 
 
    }); 
 
})
.box { 
 
    left: 0; 
 
    width: 100px; 
 
    height: 100px; 
 
    background: green; 
 
    position: relative; 
 
    transition: left 1s; 
 
}
<button>Click me!</button> 
 
<div class="box"></div>

相关问题