jq实现锚点跳转滑动效果小记

页面正常使用a标签链接到对应的元素

	<div class="top">
		<a href="#a1">1111a>
		<a href="#a2">2222a>
		<a href="#a3">3333a>
		<a href="#a4">4444a>
	div>
	<div class="content">
		<div id="a1">1111div>
		<div id="a2">2222div>
		<div id="a3">3333div>
		<div id="a4">4444div>
	div>

js中添加这个方法就可以了

$(function(){
     //锚点跳转滑动效果
     $('a[href*="#"],area[href*="#"]').click(function() {
         console.log(this.pathname)
         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 targetOffset = $target.offset().top;
                 $('html,body').animate({ scrollTop: targetOffset }, 200);
                 return false;
             }
         }
     });
 })

你可能感兴趣的:(js/jq)