【问题标题】:Maintain div scroll position on postback with html/javascript使用 html/javascript 在回发时保持 div 滚动位置
【发布时间】:2011-02-08 21:00:24
【问题描述】:

有没有办法在不使用 asp 的情况下保持回发时的 div 滚动位置?到目前为止,我只找到了使用 asp 的解决方案。

【问题讨论】:

    标签: javascript html postback maintainscrollpositionon


    【解决方案1】:

    http://blogs.x2line.com/al/articles/156.aspx

    <!doctype html>
    <html>
    <head>
    <title></title>
    
    <script language="javascript">
        // function saves scroll position
        function fScroll(val)
        {
            var hidScroll = document.getElementById('hidScroll');
            hidScroll.value = val.scrollTop;
        }
    
        // function moves scroll position to saved value
        function fScrollMove(what)
        {
            var hidScroll = document.getElementById('hidScroll');
            document.getElementById(what).scrollTop = hidScroll.value;
        }
    </script>
    </head>
    
    <body onload="fScrollMove('div_scroll');" onunload="document.forms(0).submit()";>
    
    <form>
    
    <input type="text" id="hidScroll" name="a"><br>
    <div id="div_scroll" onscroll="fScroll(this);" style="overflow:auto;height:100px;width:100px;">
    
       .. VERY LONG TEXT GOES HERE
    
    </div>
    </form>
    </body>
    </html>
    

    【讨论】:

    • 我尝试设置他的示例,用lipsum 填充它,但它似乎不起作用。源页面上的 cmets 听起来也不太乐观。你试过了吗?
    【解决方案2】:

    也许这个 javascript 代码对你有用

            function loadScroll ()
            {
                var m = /[&?]qs\=(\d+)/.exec (document.location);
                if (m != null)
                    myDiv.scrollTop = parseInt (m[1]);
            }
    
            function saveScroll ()
            {
                var form = document.getElementById ("myForm");
                var sep = (form.action.indexOf ("?") == -1) ? "?" : "&";
                form.action += sep + "qs=" + myDiv.scrollTop;
            }
    

    现在,您可以观察“提交”事件以将位置保存在“动作”属性中:

            document.getElementById ("myForm").addEventListener ("submit", saveScroll, false);
    

    在你的身体标签中......

    <body onload="loadScroll ();">
        ....
    </body>
    

    我现在无法测试代码,但我想你明白了。

    【讨论】:

      猜你喜欢
      • 2010-11-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-03
      • 2015-09-10
      • 1970-01-01
      • 2017-11-13
      相关资源
      最近更新 更多