JQuery 页面滚动动画仅适用于镶边

JQuery page scroll animation only works in chrome

本文关键字:适用于 动画 滚动 JQuery      更新时间:2023-09-26

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

答.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>

乙.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();
        }
    });

试试这个。您必须在页面加载数据后滚动。

if (window.location.hash) {
     $('html, body').show();
      $('html, body').animate({ scrollTop: $('html, body')[0].scrollHeight }, 1000);
     }