2013-07-17 62 views
0

我想在我的網站上放置一個「向上滾動」按鈕,並且出於某種原因它無法正常工作。該按鈕確實出現在頁面上,但無論什麼原因,只要我嘗試點擊它,它都會將我重定向到網站的首頁。我不知道我在做什麼錯。向上滾動按鈕,網站無法正常工作

<script> 
$(function(){$.fn.scrollToTop=function(){$(this).hide().removeAttr("href");if($(window).scrollTop()>="100"){$(this).fadeIn("slow")}var scrollDiv=$(this);$(window).scroll(function(){if($(window).scrollTop()<="1000"){$(scrollDiv).fadeOut("slow")}else{$(scrollDiv).fadeIn("slow")}});$(this).click(function(){$("html, body").animate({scrollTop:0},"slow")})}}); 
$(function(){$("#toTo_button").scrollToTop();}); 
</script> 
<style> 
#toTo_button { width:70px;text-align:center;padding:5px;position:fixed;bottom:10px;right:12px;cursor:pointer;color:#666;text-decoration:none; } 
#ups a img { opacity:0.7; -moz-opacity:0.7; filter:alpha(opacity=70); } 
#ups a:hover img { opacity:1.0; -moz-opacity:1.0; filter:alpha(opacity=100); } 
</style> 
<div id="ups"> 
<a href="/" id="toTo_button"><img src="http://full4dl.ucoz.com/Support/ups.png" alt="" /></a> 
</div> 
+0

您是否根據點擊事件調用函數? – Arun

+0

你真的應該更好地格式化和縮進你的代碼。另外,使用http://jsfiddle.net來準備一個人們可以輕鬆運行和編輯的例子。 – jnylen

+0

我們的任何代碼有幫助嗎?如果是這樣,你可以標記一個作爲解決方案,或讓我們知道當你試圖運行它時發生了什麼。謝謝! –

回答

0

你必須阻止默認動作當你點擊錨,如<a href="/" ...一定會重定向到主頁:

$(function() { 
    $.fn.scrollToTop = function() { 
     $(this).hide().removeAttr("href"); 
     if ($(window).scrollTop() >= "100") { 
      $(this).fadeIn("slow") 
     } 
     var scrollDiv = $(this); 
     $(window).scroll(function() { 
      if ($(window).scrollTop() <= "1000") { 
       $(scrollDiv).fadeOut("slow") 
      } else { 
       $(scrollDiv).fadeIn("slow") 
      } 
     }); 
     $(this).click(function (e) { 
      e.preventDefault();   // ding ding ding 
      $("html, body").animate({ 
       scrollTop: 0 
      }, "slow") 
     }) 
    } 
}); 
$(function() { 
    $("#toTo_button").scrollToTop(); 
}); 
0

你有幾個問題與您的代碼。

首先,您必須通過將該函數綁定到單擊事件來觸發該函數。其次,當你觸發那個點擊事件時,你應該傳遞事件並且調用event.preventDefault()。這可以防止瀏覽器自動調用重定向。

0

在定位標記的點擊事件中使用event.preventDefault(),這將停止默認重定向到網站的主頁(正如您編寫的a href="/")。

這應該可以解決問題。