2016-04-08 29 views
0

我知道jQuery中已經有一個函數可以讓你動畫了。但是,我想知道如何讓一個元素輕鬆進入我希望它與javascript一致的位置。我有一個簡單的功能,如果你點擊一個按鈕,一個div會出現,它會滑落一點點。問題是有時滑動下來的動畫有點波動,但其他時候很好。是否有一種方法可以讓我每次點擊按鈕都能使動畫順暢?如何在javascript中爲動畫製作緩動功能?

片段

document.querySelector('div#ex2 button').onclick = function() { 
 
    var counter; 
 

 
    // shows the div 
 
    document.querySelector('div#reveal').style.display = "block"; 
 

 
    // used to decrease bottom position 
 
    var dec = 20; 
 
    counter = setInterval(moveD, 10); 
 

 
    // moves the div down 
 
    function moveD() { 
 
     dec -= 2; 
 
     document.getElementById('reveal').style.bottom = dec + "px"; 
 
     if (dec < 1) { 
 
     clearInterval(counter); 
 
     log('function is done'); 
 
     document.getElementById('reveal').style.bottom = 0; 
 
     } // moveD if 
 
    } // function moveD 
 

 

 
}; // onclick function
div#reveal { 
 
    height: 100px; 
 
    width: 300px; 
 
    background: purple; 
 
    padding: 5px; 
 
    position: relative; 
 
    bottom: 20px; 
 
    display: none; 
 
    color: white; 
 
    text-align: center; 
 
    vertical-align: center; 
 
    margin: 10px 0; 
 
}
<div id="ex2"> 
 
    <h2>Example 2</h2> 
 
    <p></p> 
 
    <h4>results:</h4> 
 
    <button>Click it</button> 
 
    <div id="reveal">This will be revealed</div> 
 
</div>

+0

JS動畫通常會有點跳動,爲了使它更平滑,您應該真正查看專門爲此目的而構建的庫。此外,CSS動畫是最流暢的動畫,只要它們得到您需要的每個人的支持即可。 – DBS

回答

0

我覺得你可以僅僅通過使用CSS動畫老老實實解決您的問題。 請記住,如果可能的話,你應該總是使用CSS來做一些事情而不是JavaScript。

w3schools link

特別(你可以下滾一點)有一個animation-timing-function你會感興趣的