可以使用JavaScript / jQuery将页面滚动到特定位置,类似于在HTML中使用
#elementId
实现跳转。当调用JS函数时,可以滚动到页面上的特定位置。#elementId
实现跳转。当调用JS函数时,可以滚动到页面上的特定位置。经过大量谷歌搜索,我发现你只需要这样做:
location.hash = "elementId"
另一种解决方案是使用 scrollIntoView() 方法。
document.getElementById("elementID").scrollIntoView();
以下是我在今天的纽约时报首页上使用浏览器控制台测试过的示例函数:
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);
window.scrollTo({ top: positionY, left: positionX, behavior: 'smooth' });
@nwillo window.scrollTo({ top: positionY, left: positionX, behavior: 'smooth' });
- jami0821