2016-04-04 111 views
-2

滚动我的代码JavaScript没有在第二次点击

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js" type="text/javascript"></script> 
<script> 
    $(document).ready(function() { 
     $("#Button1").click(function() { 
      $('html, body').animate({ 
       scrollTop: $("#Div1").offset().top 
      }, 2000); 
     }); 
     $("#Button2").click(function() { 
      $('html, body').animate({ 
       scrollTop: $("#Div2").offset().top 
      }, 2000); 
     }); 
     $("#Button3").click(function() { 
      $('html, body').animate({ 
       scrollTop: $("#Div3").offset().top 
      }, 2000); 
     }); 
    }); 
</script> 

这部分当我到达的页面,并单击其中一个按钮工作正常,但是当我需要再次单击它穿上”工作。

有什么想法?

+0

完全无关的问题,但让你有一个事件监听器控制,你可以很容易地简化这个代码全部滚动,而不是每个按钮都有一个单独的点击功能。 – APAD1

+0

html是什么样的? – epascarello

回答

0

它必须与您的HTML有关。我把你的代码放在下面的代码片段中,它可以工作。

$(document).ready(function() { 
 
     $("#Button1").click(function() { 
 
      $('html, body').animate({ 
 
       scrollTop: $("#Div1").offset().top 
 
      }, 2000); 
 
     }); 
 
     $("#Button2").click(function() { 
 
      $('html, body').animate({ 
 
       scrollTop: $("#Div2").offset().top 
 
      }, 2000); 
 
     }); 
 
     $("#Button3").click(function() { 
 
      $('html, body').animate({ 
 
       scrollTop: $("#Div3").offset().top 
 
      }, 2000); 
 
     }); 
 
    });
.space { 
 
    height: 100px; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 
 
<button id="Button1">Button1</button> 
 
<button id="Button2">Button2</button> 
 
<button id="Button3">Button3</button> 
 

 

 
<div class="space"></div> 
 
<div id="Div1">Div1</div> 
 
<div class="space"></div> 
 
<div id="Div2">Div2</div> 
 
<div class="space"></div> 
 
<div id="Div3">Div3</div> 
 
<div class="space"></div> 
 
<div class="space"></div> 
 
<div class="space"></div>

-2

它看起来从我到底行不行,我已经创造了这个的jsfiddle你。

我相信,按钮不起作用,因为你可能已经在你想要滚动到的地方。

jsfiddle

代码段

$(document).ready(function() { 
 
    $("#Button1").click(function() { 
 
    $('html, body').animate({ 
 
     scrollTop: $("#Div1").offset().top 
 
    }, 2000); 
 
    }); 
 
    $("#Button2").click(function() { 
 
    $('html, body').animate({ 
 
     scrollTop: $("#Div2").offset().top 
 
    }, 2000); 
 
    }); 
 
    $("#Button3").click(function() { 
 
    $('html, body').animate({ 
 
     scrollTop: $("#Div3").offset().top 
 
    }, 2000); 
 
    }); 
 
});
.container { 
 
    height: 1000px; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 

 
<body> 
 
    
 
    
 
<div id="Div1">1</div> 
 
<div id="Div2">2</div> 
 
<div id="Div3">3</div> 
 

 
<div class="container"> 
 
</div> 
 
<div id="Button1">click1</div> 
 
<div id="Button2">click2</div> 
 
<div id="Button3">click3</div> 
 
    
 
    
 
</body>

+0

还没有工作 – user3494214

相关问题