Html 如何使用javascript重置div中的滚动位置

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19492776/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 14:39:26  来源:igfitidea点击:

how to reset scroll position in a div using javascript

javascripthtmlcssdojo

提问by Anand Jha

I am working on a mobile hybrid application.

我正在开发一个移动混合应用程序。

In my html page, I have 3 tabs. When clicking a tab, the content of the scrollable div gets changed. My problem is when I scroll down the content of div (view) and click another tab, the content disappears (but the content is there). Please help me so I can reset the div scroll position when clicking any tab.

在我的 html 页面中,我有 3 个标签。单击选项卡时,可滚动 div 的内容会更改。我的问题是当我向下滚动 div (view) 的内容并单击另一个选项卡时,内容消失(但内容在那里)。请帮助我,以便我可以在单击任何选项卡时重置 div 滚动位置。

Please give me suggestions only with JavaScript or CSS, not with JQuery as I am not using the JQuery library.

请仅使用 JavaScript 或 CSS 给我建议,不要使用 JQuery,因为我没有使用 JQuery 库。

采纳答案by Anand Jha

Finally this worked for me

最后这对我有用

function resetScrollPos(selector) {
  var divs = document.querySelectorAll(selector);
  for (var p = 0; p < divs.length; p++) {
    if (Boolean(divs[p].style.transform)) { //for IE(10) and firefox
      divs[p].style.transform = 'translate3d(0px, 0px, 0px)';
    } else { //for chrome and safari
      divs[p].style['-webkit-transform'] = 'translate3d(0px, 0px, 0px)';
    }
  }
}
resetScrollPos('.mblScrollableViewContainer');

Calling this function after transition between view ,will reset my scroll position.

在视图之间转换后调用此函数,将重置我的滚动位置。

回答by Shadow

Without seeing code, i can just guess. If you want to reset the scroll position you can simply use

没有看到代码,我只能猜测。如果你想重置滚动位置,你可以简单地使用

window.scrollTo(0,0); 

add this code to your each tab click functions so that when ever you click any tab, it resets to top.

将此代码添加到您的每个选项卡单击功能中,以便无论何时单击任何选项卡,它都会重置到顶部。

If you have any specific div that has overflow property

如果您有任何具有溢出属性的特定 div

var myDiv = document.getElementById('specificDiv');
myDiv.scrollTop = 0;

回答by Hamid Bahmanabady

It is easy

这很容易

 <div id="test" style="height:150px; width:600px;overflow-y:auto;background-color:gray;">
     <div style="width:150px;height:500px; background-color:green;"></div>
 </div>
document.getElementById('test').scrollTop =0;
document.getElementById('test').scrollTop =0;