2016-12-29 64 views
-1

下面的Javascript有什么作用?有人能解释一下这个平滑的滚动API中的每一行吗?NoobProgramer =“需要对此JQUERY平滑滚动代码进行解释”

$('a').click(function(){  //when you click 'a' run this function 
     $('html, body').animate({    // animate what is in the html and body? 
     scrollTop: $($(this).attr('href')).offset().top //grab coordinates? 
     }, 800);        // scroll speed? 
     return false;      // not sure what this means 
    }); 
+2

'返回false;'取消点击动作。关于animate的文档:http://api.jquery.com/animate/ jquery多选择器https://api.jquery.com/multiple-selector/ – epascarello

+0

几乎所有的好东西......'$('html,body')'是DOM选择器(我认为HTML不包括在内)......并且“返回false”会阻止“a”按预期工作(当您单击“a”元素时,您正在执行自定义行为,所以您不需要默认行为) – Hackerman

+0

'return false'与'function(ev){ev.preventDefault();'相同,就像@epascarello所说的那样,只是当你点击链接时它不会重定向到'href =“”' – Baruch

回答

3

好吧,让我们的开始,第2行是正确的从你的调查

$('a').click(function(){  //when you click 'a' run this function 
    $('html, body').animate({  // animate the actual body and html element? 

下一行是有点棘手。让我们把它分解

$(this).attr("href") 

点击的元素(一)href属性值(在这种情况下,它可能是这样的#test1的或#TEST2

$($(this).attr("href") 

如果以上的值为“#TEST1 “选择变成$(”#TEST1' ),这符合项目与id=test1

$().offset().top 

所有元素你有该元素的坐标文件偏移方法,一个个的e变量是距离文档顶部的距离的顶部。

因此下一行会发现,需要滚动

 scrollTop: $($(this).attr('href')).offset().top 
    }, 800);   // this is the scroll speed 
    return false; // this will stop the anchor element from executing the default functionality, which is actually navigating to the href specified. 
}); 

我希望这有助于像素总量:P

+0

谢谢!我想我现在明白了。 –