繁体   English   中英

滚动到元素中的特定 y 位置

[英]Scroll to a specific y position in element

我在 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);”。

感谢您的帮助!

当您应该针对不同的内容时,您的代码将 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 属性的原因的更多信息。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM