2016-04-04 118 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

相關問題