javascript - jQuery 页面滚动动画只适用于 chrome

标签 javascript jquery html google-chrome

我有以下两个 html 文件。当您单击第一页 (a.html) 中的链接时,它将打开第二页 (b.html) 并向下滚动到相关位置。我在滚动中添加了一个 JQuery 动画。这在 chrome 中完美运行,但在其他浏览器(如 firefox 和 IE)中则不行。

a.html

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Untitled Document</title>




    </head>

    <body>

       <a href="b.html#elementID">Jump</a>

</body>
</html>

b.html

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>

<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<script type="text/javascript">
    $(document).ready(function() {
        $('html, body').hide();

        if (window.location.hash) {
            setTimeout(function() {
                $('html, body').scrollTop(0).show();
                $('html, body').animate({
                    scrollTop: $(window.location.hash).offset().top
                    }, 1000)
            }, 0);
        }
        else {
            $('html, body').show();
        }
    });
</script>


</head>

<body>





<div style="margin-top:4000px" id="elementID">AAAAAAAAAAAAA</div>
<h1>AAAAAAA</h1>
<h1>AAAAAAA</h1>
<h1>AAAAAAA</h1>
<h1>AAAAAAA</h1>
<h1>AAAAAAA</h1>
<h1>AAAAAAA</h1>
<h1>AAAAAAA</h1>
<h1>AAAAAAA</h1>
<h1>AAAAAAA</h1>
<h1>AAAAAAA</h1>
<h1>AAAAAAA</h1>
<h1>AAAAAAA</h1>
<h1>AAAAAAA</h1>
<h1>AAAAAAA</h1>
<h1>AAAAAAA</h1>
<h1>AAAAAAA</h1>

</body>
</html>

最佳答案

默认情况下,Firefox 强制浏览器转到散列标签的位置。您需要在页面加载时重置 scrollTop 然后制作这样的动画:

$(document).ready(function() {
        $('html, body').hide();

        if (window.location.hash) {
            setTimeout(function() {
                $('html, body').scrollTop(0).show();
                $('html, body').prop('scrollTop',0).animate({
                    scrollTop: $(window.location.hash).offset().top
                    }, 1000)
            }, 0);
        }
        else {
            $('html, body').show();
        }
    });

关于javascript - jQuery 页面滚动动画只适用于 chrome,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27619779/

相关文章:

javascript - 在不刷新的情况下在同一 php 页面中传递 var

javascript - Jquery数据表: Removing row redirects to first page every time

javascript - 在 php 中检测浏览器、版本和平台的可靠方法

javascript - mousemove 自动触发 IE 9

javascript - 对象 HTMLAnchorElement] 没有方法 'attr'

html - 如何在表格边框中使用宽度?

javascript - 使用 Jquery 在 Icon 中滑动

javascript - ajax 创建的链接不像硬编码链接那样工作(CSS 对象类操作)

javascript - 将图像 'src' 添加到 '<a>' 标签

html - 字体系列在 Chrome 中自动更改为 "undefined,sans-serif!important"