简体   繁体   English

如何仅使用 Javascript 滚动回左上角?

[英]How to scroll back to the top left using only Javascript?

My problem is simple: I have a div container, with a property of overflow:auto , in mobile I see the scroll bar because my elements are out of the container, I can scroll to the right or left.我的问题很简单:我有一个 div 容器,其属性为overflow:auto ,在移动设备中我看到滚动条,因为我的元素不在容器中,我可以向右或向左滚动。 I want that when I click an item in the top right, it gets placed in the head of the list (unshift), and the container goes back to its default position where the scrollLeft is 0. What I am doing is:我希望当我单击右上角的一个项目时,它会被放置在列表的头部(取消移位),并且容器返回到其默认的 position,其中scrollLeft为 0。我正在做的是:

myElement.scrollLeft = 0;

But it is not working.但它不起作用。 This is the whole code I have:这是我的全部代码:

function showDetails(i) {

  // Important 
  cdiscountHeaderOptions.scrollLeft = 0;

  if (/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)) {
    let updatedData = data.filter(function (item) {
      return item.id - 1 !== i;
    });
    let selectedItem = data.filter(function (item) {
      return item.id - 1 === i;
    })[0];
    updatedData.unshift(selectedItem);
    renderData(updatedData);
  }

  detailsContainers.style.display = 'flex';

}

I tried also:我也试过:

myElement.scrollTo(0,0); 

But I got an error: scrollTo is not a function.但是我得到一个错误:scrollTo 不是 function。

Any help would be much appreciated.任何帮助将非常感激。

What I would do is place an empty div at the top <div id="scrollToTop"></div> of your HTML page and then in your js code, you can simply say document.getElementById("scrollToTop").scrollIntoView();我要做的是在您的 HTML 页面的顶部<div id="scrollToTop"></div>放置一个空的 div,然后在您的 js 代码中,您可以简单地说document.getElementById("scrollToTop").scrollIntoView();


UPDATED ANSWER更新的答案

Try putting a div where you want to scroll, make it position absolute so it's at a specific position, then you can use the .scrollIntoView();尝试将 div 放在要滚动的位置,使其成为绝对值 position,使其位于特定的 position,然后您可以使用.scrollIntoView(); function function


UPDATED ANSWER更新的答案

window.scrollTo(0,0)

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

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