javascript - 网站无法正常工作的向上滚动按钮

标签 javascript html css scroll

我想在我的网站上放置一个“向上滚动”按钮,但由于某种原因它无法正常工作。该按钮确实出现在页面上,但无论出于何种原因,每当我尝试单击它时,它只会将我重定向到该站点的首页。我不知道我做错了什么。

<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>

最佳答案

您必须阻止单击 anchor 时的默认操作,如 <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();
});

关于javascript - 网站无法正常工作的向上滚动按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17701912/

相关文章:

javascript - 使用Dreamweaver的JavaScript中的语法错误

javascript - 使用 rhino 运行 jshint

javascript - 将图像固定在具有特定坐标、比例的图像上?

css - Div 调整大小不适用于 three.js

html - 当单词具有不同数量的带有 CSS 的字符时,如何确保单词间隔均匀?

html - 如何设置/修改 Django 文件字段的样式?

javascript - 在 ruby​​ on rails 4 元素中实现页面特定的 java 脚本和 CSS

javascript - 在javaScript中获取Div的最外层父id

php 从数据库中获取列值并显示在 html 表列中

javascript - HTML 5 - 如何缩放 Canvas 背景图像