我正在尝试在我的网站上放置一个“向上滚动”按钮,由于某种原因它无法正常工作。该按钮确实出现在页面上,但无论出于何种原因,每当我尝试点击它时,它只会将我重定向到网站的首页。我不知道我做错了什么。
<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 :(得分: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();
});
答案 1 :(得分:0)
您的代码存在一些问题。
首先,您必须通过将其绑定到click事件来触发该函数。
$('#toTo_button').click(function(event) {
//do your scroll magic here
});
其次,当您触发该点击事件时,您应该传递该事件并致电event.preventDefault()
。这可以防止浏览器自动调用重定向。
答案 2 :(得分:0)
对锚标记的点击事件使用event.preventDefault()
,这将停止默认重定向到网站的主页(正如您所写的a href="/"
)。
这应解决问题。