我正在构建一个单页网站,我需要导航链接来平滑滚动到网站的不同页面或部分。我使用的 javascript 在 Chrome 和 Safari 中完美运行,但在 FireFox 中,它无法滚动到正确的位置。我的所有 anchor 都在 html 中,但这是我正在使用的 javascript。我在 Firefox 兼容性方面缺少什么吗?
<!-- SMOOTH SCROLL -->
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$(".contactLink").click(function(){
if ($("#contactForm").is(":hidden")){
$("#contactForm").slideDown("slow");
}
else{
$("#contactForm").slideUp("slow");
}
});
});
function closeForm(){
$("#messageSent").show("slow");
setTimeout('$("#messageSent").hide();$("#contactForm").slideUp("slow")', 2000);
}
$(document).ready(function() {
function filterPath(string) {
return string
.replace(/^\//,'')
.replace(/(index|default).[a-zA-Z]{3,4}$/,'')
.replace(/\/$/,'');
}
$('a[href*=#]').each(function() {
if ( filterPath(location.pathname) == filterPath(this.pathname)
&& location.hostname == this.hostname
&& this.hash.replace(/#/,'') ) {
var $targetId = $(this.hash), $targetAnchor = $('[name=' + this.hash.slice(1) +']');
var $target = $targetId.length ? $targetId : $targetAnchor.length ? $targetAnchor : false;
if ($target) {
var targetOffset = $target.offset().top;
$(this).click(function() {
$('html, body').animate({scrollTop: targetOffset}, 1000);
var d = document.createElement("div");
d.style.height = "101%";
d.style.overflow = "hidden";
document.body.appendChild(d);
window.scrollTo(0,scrollToM);
setTimeout(function() {
d.parentNode.removeChild(d);
}, 10);
return false;
});
}
}
});
});
最佳答案
试试这个:
$(".anchor").click(function(e) {
e.preventDefault();
anchor = $(this).attr('href');
$("html, body").animate({
'scrollTop': $(anchor).offset().top
}, 1000);
});
适用于像
这样的 anchor<a class="anchor" href="#div1">click</a>
<div id="div1">texttext</div>
关于javascript - 我的 javascript 平滑滚动无法滚动到 Firefox 中的正确位置,有人知道我做错了什么吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30895406/