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

时间:2015-08-11 08:06:23

标签: javascript iphone modal-dialog mobile-safari hashchange

这可能是一个有点奇怪的具体问题。

情况:

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

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

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

测试代码

这就像我能够做到的那样减少了。

<!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个小时数,但是还没有找到这个特定问题,或者确实是一个有效的解决方案。如果我错过了回答我问题的现有帖子,请随意用手指拍我并指出正确的方向。

编辑:为了澄清,打开弹出窗口按预期工作,并且不会导致任何&#34;自动滚动&#34;。

1 个答案:

答案 0 :(得分:0)

这肯定与拥有&#34;#&#34;为&#34; a href&#34;代码中的值。另外,我看到&#34; ##&#34;在你的代码中有一个ID的名称,我相信这个的原因。尝试使用其他一些名称约定。当你写ID时,你不需要给#34;#&#34;在HTML代码中。尝试在这些方面工作,它可能适合你。

谢谢!

相关问题