在移动Safari中使用后退按钮关闭模式时,页面滚动到顶部

Page scrolls to top when closing modal using back button in mobile Safari

本文关键字:模式 顶部 滚动 Safari 移动 按钮      更新时间:2023-09-26

这可能是一个有点奇怪的特定问题。

这句话的语境是:

我有一个页面与position:fixed模态对话框(实际上几个,但这是无关的问题,只要我已经能够确定)。当单击某个链接时,模态打开。脚本监听hashchange事件,以便在用户点击后退按钮时关闭模态。

预期的行为是,当退出对话框时,页面返回到打开模态之前的滚动位置。这种情况发生在我测试过的几乎所有现代浏览器中(桌面FF, Chrome, IE9/10/11和Safari,以及Chrome for Android)。

在iPhone/移动Safari上,页面会滚动回顶部。

<<p> 测试代码/strong>

这是我能做的最简单的了。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta http-equiv="content-type" content="text/html, charset=utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Modal test</title>
</head>
<body>
<h1>Header</h1>
<p>Enough<br>content<br>to<br>cause<br>some<br>scrolling</p>
<br><br><br><br><br><br><br>
<br><br><br><br><br><br><br>
<br><br><br><br><br><br><br>
<h1>Header</h1>
<p><a href="##popup" class="js-open-popup">Open popup</a></p>
<p>Enough<br>content<br>to<br>cause<br>some<br>scrolling<br>
<br><br><br><br><br><br>
<br><br><br><br><br><br>
<br><br><br><br><br><br>

<div id="#popup" style="background:#fff; width:300px; height:100px; border:2px solid #000; position:fixed; top:50px; left:50px; display:none">
    Modal dialog.<br>
    Hitting 'back' should close this modal.<br><br>
    <a href="javascript:void(0)" class="js-close-popup">Close modal</a>
</div>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script type="text/javascript">
    (function($){
        $(document).ready(function(){
            $('.js-close-popup').click(function(ev){
                window.history.back();
                return false;
            });
            $('.js-open-popup').click(function(ev){
                $('#''#popup').fadeIn(400);
            });
        });
        $(window).on('hashchange', function(){
            hash = window.location.hash.replace('#','');
            if(hash == '' || hash.lastIndexOf('#', 0) !== 0){
                $('#''#popup').fadeOut(400);
            }
        });
    })(jQuery);
</script>
</body>
</html>

我想做的是取消iphone上的滚动到顶部,如果可能的话,在不改变太多弹出窗口的后退按钮逻辑(或破坏任何其他浏览器中的东西)的情况下。

我已经搜索了X个小时,但还没能找到一个提到这个特定的问题,或者确实是一个解决方案,工作。如果我错过了一个可以回答我问题的现有线程,请随意拍打我的手指并为我指出正确的方向。

EDIT:澄清一下,打开弹出窗口的工作原理与预期一样,不会导致任何"自动滚动"

这肯定与代码中使用"#"表示"a href"值有关。此外,我在你的代码中看到一个"##"作为ID的名称,我认为这是原因。尝试使用其他命名约定。当您编写ID时,您不需要在HTML代码中给出"#"。试着处理这些行,它可能对你有用。

谢谢! !