包含锚点平滑滚动效果/解决锚点链接碰到固定定位问题/导航选中背景变色/固顶/返回顶部效果全

<script type="text/javascript">
    $(function() {
        //锚点平滑滚动效果
        $('a[href*=#],area[href*=#]').click(function() {
            if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') && location.hostname == this.hostname) {
                var $target = $(this.hash);
                $target = $target.length && $target || $('[name=' + this.hash.slice(1) + ']');
                if ($target.length) {
                    //解决锚点链接碰到固定定位问题
                    var w = $(window).width();
                    var targetOffset = $target.offset().top;
                    if (w < 992) {
                        targetOffset = $target.offset().top - 60;
                    } else {
                        targetOffset = $target.offset().top - 80;
                    }
                    //解决锚点链接碰到固定定位问题结束
                    $('html,body').animate({
                        scrollTop: targetOffset
                    }, 1000);
                    return false;
                }
            }
        });
        //导航选中背景变色
        $('.nav li a').click(function() {
            $(this).addClass('on').parent().siblings().find('a').removeClass('on');
            //点击导航,导航隐藏
            $(".navbar-collapse").removeClass("in")
        });
        //固顶
        $(window).scroll(function() {
            var top = $(window).scrollTop();
            var w = $(window).width();
            if (top >= 450) {
                $(".navbar-default").addClass("x_fixed");
            } else {
                $(".navbar-default").removeClass("x_fixed");
            }
        });
        //返回顶部
        $(window).scroll(function() {
            if ($(window).scrollTop() > 100) {
                $("#toTop").fadeIn(1500);
            } else {
                $("#toTop").fadeOut(1500);
            }
        });
        //当点击跳转链接后,回到页面顶部位置
        $("#toTop").click(function() {
            $('body,html').animate({
                scrollTop: 0
            }, 1000);
            return false;
        });

    })
</script>

 

posted @ 2019-08-05 14:52  夏小夏吖  阅读(636)  评论(1编辑  收藏  举报