锚链接加动画总结

<!--html-->
<div id="top" name="top" style="height:3000px;"></div>
<a href="#top">回顶部</a>   <!--  设置锚链接跳转地方的id  -->

方法一

$('a').click(function(){
    $('html, body').animate({
        scrollTop: $( $.attr(this, 'href') ).offset().top
    }, 500);
    return false;
});

延伸

$(document).on('click', 'a', function(event){
    event.preventDefault();  //  阻止默认事件发生
    $('html, body').animate({
        scrollTop: $( $.attr(this, 'href') ).offset().top
    }, 500);
});

方法二

$('a').click(function(){
        $(document).animate({
                  /* 点击对象的锚链接*/
            scrollTop:$(this.hash).offset().top
        },500)
        return false;
    })
如果你的目标元素没有ID,也可以用设置name来链接:
$('a').click(function(){
    $('html, body').animate({
        scrollTop: $('[name="' + $.attr(this, 'href').substr(1) + '"]').offset().top
    }, 500);
    return false;
});
为了提高性能,应该缓存该$(‘html,body’)选择器,以便每次单击锚点时都不会运行:
var $root = $('html, body');
$('a').click(function() {
    $root.animate({
        scrollTop: $( $.attr(this, 'href') ).offset().top
    }, 500);
    return false;
});
如果要更新链接地址URL,在animate回调中执行即可
var $root = $('html, body');
$('a').click(function() {
    var href = $.attr(this, 'href');
    $root.animate({
        scrollTop: $(href).offset().top
    }, 500, function () {
        window.location.hash = href;
    });
    return false;
});
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值