2015-10-04 109 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>