2015-12-11 74 views
-2

我正在爲一個學校項目在網站上工作,並且在使用javascript時遇到了問題。我不是js的粉絲,因爲我總是遇到問題,我似乎無法讓他們在沒有幫助的情況下找到答案,但這是該項目的要求之一。我試圖讓頁面中的標題從頁面左側移入,並在頁面加載時進入中心。這裏是我的代碼:獲取javascript函數工作

JS:

function animate() { 
    function movetext() { 
     obj = document.getElementById('spacer'); 
     obj.style.position ='relative'; 
     obj.style.left = '-100px'; //still needs to be adjusted 
    } 

    function moveright() { 
     obj.style.alignContent="center"; 
     obj.style.animation="move 2s"; 
    } 
} 

HTML:

<!DOCTYPE html> 

<html lang="en"> 

<head> 
    <meta charset="utf-8"> 
    <title>Lockport, NY - Activities</title> 
    <link rel="stylesheet" href="project.css"> 
    <link href='https://fonts.googleapis.com/css?family=Oleo+Script+Swash+Caps' rel='stylesheet' type='text/css'> 
</head> 

<body onload="animate();"> 

<!-- Background --> 
<div class="background"> 

    <!-- Navigation --> 
    <?php 
     include 'includes/nav.php'; 
    ?> 

    <!-- Title --> 
    <div id="spacer"><p span class="titles">Activities...</p></div> 

    <div id="wrapper"> 
     <div id="main"> 
      //code removed for readability 

     </div> 

    <!-- Footer --> 
    <?php 
     include 'includes/footer.php'; 
    ?> 

    </div> 

</div> 
</body> 
<script src="project1.js"></script> 
</html> 

我知道我不是最偉大的,當涉及到編碼,我知道它可能是一個簡單的修復,但我找不到它。幫助表示讚賞。

回答

1

你可以用CSS動畫很容易做到這一點:

setTimeout(function() { 
 
    document.getElementById('spacer').classList.add('show'); 
 
}, 100);
#spacer { 
 
    position: absolute; 
 
    right: 100%; 
 
    transition: right 3s; 
 
} 
 

 
#spacer.show { 
 
    right: 50%; 
 
}
<div id="spacer"> 
 
    <p class="titles"> 
 
    Hello 
 
    </p> 
 
</div>

0

這個更好的解決方案是使用兩個類(如.centerpos,.title僞),只是分配通過js將文本置於中心的樣式。

所以它看起來類似的東西:

<!DOCTYPE html> 
<html lang="en"> 
    <head> 
     <meta charset="utf-8"> 
     <title>Lockport, NY - Activities</title> 
     <link href='https://fonts.googleapis.com/css?family=Oleo+Script+Swash+Caps' rel='stylesheet' type='text/css'> 
    </head> 
    <style> 
     .title { 
      position: absolute; 
      left: -100px; 
      transition: left 2s; 
     } 
     .title.centerpos { 
      left: 50%; 
      transform: translate(-50%, 0); 
     } 
    </style> 
    <body onload="document.querySelector('.title').classList.add('centerpos');"> 
     <div class="background"> 
      <div id="spacer"><p span class="titles title">Activities...</p></div> 
      <div id="wrapper"> 
       <div id="main"> 
        //code removed for readability 

       </div> 
      </div> 
     </div> 
    </body> 
</html>