我的网站上有一个垂直导航点击功能,该功能在 Firefox、IE10 和 IE9 中运行良好,但在 Chrome 或 Safari 中不起作用。检查页面时我没有收到任何 chrome 错误。
我从 FF 和 Chrome 中获得此代码的原始代码,但由于我已经 fork 了它,因此该代码在 Chrome 中不再起作用。
原始代码: Scrolling to the next element
原jsFiddle:http://jsfiddle.net/Pm3cj/3/
我的Jsfiddle:https://jsfiddle.net/hjb6631d/1/
HTML:
<div style="height: 5000px">
<section class="cover" style="height: 100px; border: 1px solid black; margin-bottom: 10px;">
<section class="controls">
<p class="prev">prev</p>
<p class="next">next</p>
1
</section>
</section>
<section class="cover" style="height: 100px; border: 1px solid black; margin-bottom: 10px;">
<section class="controls">
<p class="prev">prev</p>
<p class="next">next</p>
2
</section>
</section>
<section class="cover" style="height: 100px; border: 1px solid black; margin-bottom: 10px;">
<section class="controls">
<p class="prev">prev</p>
<p class="next">next</p>
3
</section>
</section>
</div>
脚本:
$('.cover:first').addClass('first-child');
$('.cover:last').addClass('last-child');
$(".next, .prev").on("click", function(e) {
// the container that will be scrolled to
var target = '.cover';
container = $(this).parent();
// am I the last .container in my group?
while (document != container[0] && container.find('~'+target, '~:has('+target+')').length == 0)
container = container.parent(); // if so, search siblings of parent instead
prevdiv = container.prevAll(target, ':has('+target+')').first();
nextdiv = container.nextAll(target, ':has('+target+')').first();
// if clicked next object
if ( $(this).hasClass('next') ) {
// no next .container found, go back to first container
if (nextdiv.length==0) nextdiv = $(document).find(target+':first');
//$(document).scrollTop(nextdiv.offset().top);
$('html').animate({scrollTop:nextdiv.offset().top},300);
}
// if clicked prev
if ( $(this).hasClass('prev') ) {
// no next .container found, go back to first container
// scroll to previous element
prevdiv = $(this).parents(target).prev(target);
// if is first element on page, then scroll to last element
if ( $(this).parents(target).hasClass('first-child') ) {
prevdiv = $(document).find(target+':last');
};
//$(document).scrollTop(nextdiv.offset().top);
$('html').animate({scrollTop:prevdiv.offset().top},300);
}
// $(this).parent().next() // this is the next div container.
return false;
});
最佳答案
问题是,在 Chrome 中(由于某种原因)无法使用
进行滚动$('html').animate({scrollTop:....
相反,你必须使用
$('body').animate({scrollTop:....
另一方面,在 Firefox 和 IE 中,情况恰恰相反。所以我建议你使用
$('body, html').animate({scrollTop:....
使其在所有浏览器中运行
编辑:您的引用和代码之间的区别在于,在引用中,使用 jQuery
函数 $(document).scrollTop
,它采用兼容性脱离你的肩膀,这是 animate({scrollTop})
做不到的
关于javascript - 点击页面滚动在 FF 中有效,但在 Chrome 中无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29827748/