2015-10-04 116 views
0

當我點擊第一個點擊我按鈕時,它跳過第二個div並直接進入第三個div - 有誰知道這是爲什麼?我認爲這可能是由於scrollTop函數可能?我希望第一次點擊我帶我到第二個div,第二個點擊我按鈕帶我到第三個div。jQuery滾動跳過div

HTML:

<!DOCTYPE html> 
<html> 
    <head> 
     <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script> 
     <link rel="stylesheet" type="text/css" href="stylesheet.css"> 
    </head> 
    <body> 
     <div class="first"> 
      <h1>My Home Screen</h1> 
      <button type="button">Click Me!</button> 
      <script> 
       $("button").click(function() { 
       $('html,body').animate({ 
       scrollTop: $(".second").offset().top}, 
       'slow'); 
       }); 
      </script> 
     </div> 
     <div class="second"> 
      <button type="button">Click Me!</button> 
      <script> 
       $("button").click(function() { 
       $('html,body').animate({ 
       scrollTop: $(".third").offset().top}, 
       'slow'); 
       }); 
      </script> 
     </div> 
     <div class="third"> 
     </div> 
    </body> 
</html> 

CSS:

h1 { 
    font-size: 12em; 
    margin-top:0; 
    text-align:center; 
    font-weight: bold; 
    color: white; 
    font-family: 'Century Gothic', CenturyGothic, AppleGothic, sans-serif; 
    text-shadow: 2px 2px 4px #000000; 
} 

.first { 
    width: auto; 
    height: 100vh; 
    background-image: url('home_screen.jpg'); 
    background-repeat: no-repeat; 
    background-attachment:fixed; 
    background-size: cover; 
} 

.second { 
    width: auto; 
    height: 100vh; 
    background-image: url('second_screen.jpg'); 
    background-repeat: no-repeat; 
    background-attachment:fixed; 
    background-size: cover; 
    } 

.third { 
width: auto; 
height: 100vh; 
background-image: url('third_screen.jpg'); 
background-repeat: no-repeat; 
background-attachment:fixed; 
background-size: cover; 
} 

回答

1

你的代碼的重寫本身。

你應該是這樣的:

<button data-go=".second">Go to 2</button> 
<button data-go=".third">Go to 3</button> 

和JavaScript應該像:

$("button").click(function() { 
    var go_to = $(this).data('go'); 

    $('html,body').animate({ 
     scrollTop: $(go_to).offset().top}, 'slow'); 
}); 

哪裏data-go =你要當按鈕被按下

滾動div的選擇

檢查此項工作JSBIN http://jsbin.com/qohucowopu/edit?html,css,js,output

0

當你直接使用「按鈕」標籤時,你們兩個腳本都在爲這兩個按鈕工作。爲避免此問題,請爲這兩個按鈕分配唯一且不同的ID。然後使用ID在腳本中調用元素。這裏是固定代碼---

<div class="first"> 
     <h1>My Home Screen</h1> 
     <button id='button1' type="button">Click Me!</button> 
     <script> 
      $("#button1").click(function() { 
      $('html,body').animate({ 
      scrollTop: $(".second").offset().top}, 
      'slow'); 
      }); 
     </script> 
    </div> 
    <div class="second"> 
     <button id='button2' type="button">Click Me!</button> 
     <script> 
      $("#button2").click(function() { 
      $('html,body').animate({ 
      scrollTop: $(".third").offset().top}, 
      'slow'); 
      }); 
     </script> 
    </div> 
    <div class="third"> 
    </div>