【问题标题】:Scroll to a specific y position in element滚动到元素中的特定 y 位置
【发布时间】:2021-12-12 20:58:12
【问题描述】:

我有一个旧版应用程序在 Edge Chromium 中以兼容模式 (IE11) 运行。页面的一部分使用 AJAX 每 10 秒自动刷新一次表。当用户滚动查看表格的结果时,它会自动刷新并且他们会在表格中失去自己的位置。由于环境非常动态,需要经常刷新。

“window.scrollTo(0,yElemnt);”不起作用,因为它试图滚动整个窗口而不是 TPicks.asp 中的表格。

function ShowPicks(){
var elmnt = ""
var yElmnt = 0


if (document.getElementById("scrollPicks")) {
  elmnt = document.getElementById("scrollPicks");
  yElmnt = elmnt.scrollTop;
}

if (window.XMLHttpRequest) {
  
  var xmlhttp = new XMLHttpRequest();
  
  xmlhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      
      document.getElementById("AutoPickDiv").innerHTML = this.responseText;
      if (document.getElementById("scrollPicks")) {
        alert(yElmnt);
        document.scrollTo(0,yElmnt);
      }
    }  
  }
}
//alert("Picks.asp");
var RandNbr = Math.round(Math.random()*10000000);
xmlhttp.open("POST", "TPicks.asp", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send("rand=" + RandNbr);

}

如何让表格只滚动?我有表格当前滚动到“elmnt.scrollTop;”内的像素位置。 AJAX 调用返回完整后的警报显示当前滚动位置也在哪里 - “alert(yElmnt);”。

感谢您的帮助!

【问题讨论】:

    标签: javascript asp-classic


    【解决方案1】:

    当您应该针对不同的目标时,您的代码会将 document.scrollTop 设置为 y 轴。您必须将表格包装在一个元素中,例如一个DIV。然后,您必须将heightoverflow-y CSS 属性应用于该元素。然后,您需要一个可以将该元素的scrollTop 属性设置为零的javascript 函数。

    查看这个 jsfiddle 以获得一个工作示例:https://jsfiddle.net/bf4zngy7/

    <div id="wrapper">
        <div id="tablewrapper" style="max-height:100px; overflow-y:scroll">
            <table border=1>
                <!-- insert your data rows here -->
            </table>
        </div>
    
        <div id="buttonwrapper">
            <button type="button" onclick="scrollToTop()"">Scroll to top</button>
        </div>
    </div>
    

    当点击按钮时,这个函数会触发:

    function scrollToTop(){
      const tablewrapper = document.getElementById('tablewrapper');
      if(tablewrapper){
        tablewrapper.scrollTop = 0;
      }
    }
    

    在我的解决方案中,您实际上并没有滚动表格,而是滚动包含表格的元素。请参阅https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollTop,了解设置元素的 scrollTop 属性为何有效的更多信息。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-12
      • 2019-12-27
      • 2014-04-08
      • 1970-01-01
      • 1970-01-01
      • 2013-03-06
      相关资源
      最近更新 更多