锚链接加动画总结

xiaoxiao2021-02-28  79

<!--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; });
转载请注明原文地址: https://www.6miu.com/read-51455.html

最新回复(0)