2016-03-18 57 views
0

我有一個上下動畫工作正常的div。我得到的問題是,每次頁面加載div開始在頁面的最頂部,然後跳轉到動畫開始後需要的位置。在錯誤的地方動畫加載

<body id="body"> 
    <div id="square"></div> 
</body> 


#body { 
    background: #000; 
} 

#square { 
    background-color: #fff; 
    margin: 0 auto; 
    position: relative; 
    width: 100px; 
    height: 100px; 
    } 

var box = document.getElementById('square'); 
TOP = (window.innerHeight - box.offsetHeight)/2; 
box.style.top = TOP; 

var down = setInterval(animateDown, 15); 
    var up; 

    function animateDown() 
    { 
     TOP += 3; 
     box.style.top = TOP + 'px'; 
     if(TOP > 900){ 
      clearInterval(down); 
      up = setInterval(animateUp, 15); 
     } 

    } 

    function animateUp() 
    { 
     TOP -= 3; 
     box.style.top = TOP + 'px'; 
     if(TOP <= (window.innerHeight - box.offsetHeight)/2){ 
      clearInterval(up); 
      down = setInterval(animateDown, 15); 
     } 

    } 

這裏是對的jsfiddle的鏈接以及>>https://jsfiddle.net/xgilmore/pLbgvc3L/

在此先感謝

+0

適合我(不在jsfiddle中) –

+0

您使用的是什麼瀏覽器? –

回答

1

這是那種一個變通的,但你可以開始盒子關爲隱藏,然後一旦你開始動畫,將其設置爲可見。 https://jsfiddle.net/pLbgvc3L/1/

function animateDown() 
    { 
    box.style.visibility = 'visible'; 

#square { 
    background-color: #fff; 
    //margin: 0 auto; 
    position: relative; 
    width: 100px; 
    height: 100px; 
    top: 20%; 
    visibility: hidden; 
    } 

噢,對不起,其實我知道是怎麼回事,它只是採取了第二次看弄明白。 top: 20%不會執行任何操作,因爲只有父元素(主體)具有明確的高度時,百分比才能起作用。像這樣https://jsfiddle.net/pLbgvc3L/2/

+0

儘管我仍然想弄清楚發生了什麼,但這確實完成了工作。 –