我试图在每个有一个smoothScroll类的按钮上添加一个.smoothScroll动画。
所以我做了这个:
// SmoothSCroll
var smoothScroll = document.querySelectorAll('.smoothScroll');
[].forEach.call(smoothScroll, function (el) {
el.addEventListener('click', function() {
var offset = $(this.hash).offset().top;
$('html, body').stop().animate({
scrollTop: offset - (window.innerHeight/2) + ($(this.hash).innerHeight()/2)
}, 400 );
return false;
});
});https://jsfiddle.net/jt2jo3pt/2/
我不知道你是否注意到了发生了什么,但是当点击触发时会有一个小闪光灯(滚动条在平滑滚动之前会稍微下降)。
但是,当我尝试像这样使用完整的Jquery时:
$('.smoothScroll').click(function(e){
var offset = $(this.hash).offset().top;
$('html, body').stop().animate({
scrollTop: offset - (window.innerHeight/2) + ($(this.hash).innerHeight()/2)
}, 400 );
return false;
});我没有这种冒泡效应:https://jsfiddle.net/34w72v1v/
您知道querySelectorAll方法会导致这个问题的原因吗?
我尽量不使用jQuery,所以我需要知道发生了什么事情来学习:)
耽误您时间,实在对不起。
发布于 2015-04-30 13:36:54
您需要在javascript中使用preventDefault()来阻止窗口移动到书签锚点:
// SmoothSCroll
var smoothScroll = document.querySelectorAll('.smoothScroll');
[].forEach.call(smoothScroll, function (el) {
el.addEventListener('click', function(el) {
el.preventDefault();
var offset = $(this.hash).offset().top;
$('html, body').stop().animate({
scrollTop: offset - (window.innerHeight/2) + ($(this.hash).innerHeight()/2)
}, 400 );
});
});return false只是jQuery事件触发e.preventDefault()和e.stopPropagation()的快捷方式。
发布于 2015-04-30 13:37:03
这是因为return false。在jQuery中,从事件处理程序返回false会防止发生默认行为。在(non-inline) JavaScript事件处理程序中,它什么也不做。有关更多信息,请参见this excellent answer。
由于您的触发器是一个<a href="#test" class="smoothScroll">Go to test</a>,单击它时,非jQuery版本将使您深入到#test元素,但在jQuery中则不是(因为默认行为被取消).因此闪光灯。
如果您在jQuery中不返回false,或者在JavaScript版本中添加e.preventDefault(),您会注意到您可以控制闪存。
https://stackoverflow.com/questions/29969155
复制相似问题