使用 Javascript / Jquery 滚动到页面上的特定位置

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6355482/
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-23 21:23:42  来源:igfitidea点击:

Scroll to a specific position on a page using Javascript / Jquery

javascriptjquery

提问by Derin

It is possible to move to a certain position on a page using #elementId. How can I do the same thing using Javascript / Jquery. When a JS function is called, I want to scroll to the specific position on that page.

可以使用 移动到页面上的某个位置#elementId。我如何使用 Javascript / Jquery 做同样的事情。当调用 JS 函数时,我想滚动到该页面上的特定位置。

采纳答案by Derin

After much googling I found that you just need to do this:

经过多次谷歌搜索,我发现你只需要这样做:

location.hash = "elementId"

回答by Josh Earl

Here's an example function that I tested on today's New York Times front pageusing the browser console:

这是我使用浏览器控制台在今天的《纽约时报》首页上测试的示例函数:

function scrollToElement(pageElement) {    
    var positionX = 0,         
        positionY = 0;    

    while(pageElement != null){        
        positionX += pageElement.offsetLeft;        
        positionY += pageElement.offsetTop;        
        pageElement = pageElement.offsetParent;        
        window.scrollTo(positionX, positionY);    
    }
}

var pageElement = document.getElementById("insideNYTimesHeader");
scrollToElement(pageElement);

回答by Prabowo Murti

Another solution is scrollIntoView()

另一种解决方案是scrollIntoView()

document.getElementById("elementID").scrollIntoView();

回答by Vivek

you can use scrollTopto scroll up.

您可以使用scrollTop向上滚动。

you can use thisplugin too

你也可以使用这个插件