如何使用 JavaScript 滚动到元素?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5007530/
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
How do I scroll to an element using JavaScript?
提问by C..
I am trying to move the page to a <div>
element.
我正在尝试将页面移动到一个<div>
元素。
I have tried the next code to no avail:
我试过下一个代码无济于事:
document.getElementById("divFirst").style.visibility = 'visible';
document.getElementById("divFirst").style.display = 'block';
采纳答案by Nikoloff
You can use an anchor to "focus" the div. I.e:
您可以使用锚点来“聚焦” div。IE:
<div id="myDiv"></div>
and then use the following javascript:
然后使用以下javascript:
// the next line is required to work around a bug in WebKit (Chrome / Safari)
location.href = "#";
location.href = "#myDiv";
回答by schpet
scrollIntoView works well:
scrollIntoView 效果很好:
document.getElementById("divFirst").scrollIntoView();
full reference in the MDN docs:
https://developer.mozilla.org/en-US/docs/Web/API/Element.scrollIntoView
MDN 文档中的完整参考:https:
//developer.mozilla.org/en-US/docs/Web/API/Element.scrollIntoView
回答by AnhSirk Dasarp
your question and the answers looks different. I don't know if I am mistaken, but for those who googles and reach here my answer would be the following:
你的问题和答案看起来不同。我不知道我是否弄错了,但对于那些用谷歌搜索并到达这里的人,我的答案如下:
My Answer explained:
我的回答解释了:
here is a simple javascript for that
这是一个简单的javascript
call this when you need to scroll the screen to an element which has id="yourSpecificElementId"
当您需要将屏幕滚动到具有 id="yourSpecificElementId" 的元素时调用此方法
window.scroll(0,findPos(document.getElementById("yourSpecificElementId")));
ie. for the above question, if the intention is to scroll the screen to the div with id 'divFirst'
IE。对于上述问题,如果目的是将屏幕滚动到 id 为 'divFirst' 的 div
the code would be: window.scroll(0,findPos(document.getElementById("divFirst")));
代码将是: window.scroll(0,findPos(document.getElementById("divFirst")));
and you need this function for the working:
你需要这个功能来工作:
//Finds y value of given object
function findPos(obj) {
var curtop = 0;
if (obj.offsetParent) {
do {
curtop += obj.offsetTop;
} while (obj = obj.offsetParent);
return [curtop];
}
}
the screen will be scrolled to your specific element.
屏幕将滚动到您的特定元素。
回答by Caveman
For Chrome and Firefox
适用于 Chrome 和 Firefox
I've been looking a bit into this and I figured this one out which somehow feels like the most natural way to do it. Of course, this is my personal favorite scroll now. :)
我一直在研究这个,我想出了这个,不知何故感觉像是最自然的方法。当然,这是我现在个人最喜欢的卷轴。:)
const y = element.getBoundingClientRect().top + window.scrollY;
window.scroll({
top: y,
behavior: 'smooth'
});
For IE, Edge and Safari supporters
对于 IE、Edge 和 Safari 支持者
Note that window.scroll({ ...options })
is not supported on IE, Edge and Safari. In that case it's most likely best to use
element.scrollIntoView()
. (Supported on IE 6). You can most likely(read: untested) pass in options without any side effects.
请注意,window.scroll({ ...options })
IE、Edge 和 Safari 不支持。在这种情况下,最好使用
element.scrollIntoView()
. (支持 IE 6)。您很可能(阅读:未经测试)传递选项而没有任何副作用。
These can of course be wrapped in a function that behaves according to which browser is being used.
这些当然可以包装在一个函数中,该函数根据所使用的浏览器来表现。
回答by Chandu
Try this:
尝试这个:
var divFirst = document.getElementById("divFirst");
divFirst.style.visibility = 'visible';
divFirst.style.display = 'block';
divFirst.tabIndex = "-1";
divFirst.focus();
e.g @:
例如@:
回答by Geri Borbás
To scroll to a given element, just made this javascript only solution below.
要滚动到给定元素,只需在下面制作此 javascript 唯一解决方案。
Simple usage:
简单用法:
EPPZScrollTo.scrollVerticalToElementById('signup_form', 20);
Engine object (you can fiddle with filter, fps values):
引擎对象(您可以修改过滤器、fps 值):
/**
*
* Created by Borbás Geri on 12/17/13
* Copyright (c) 2013 eppz! development, LLC.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
*/
var EPPZScrollTo =
{
/**
* Helpers.
*/
documentVerticalScrollPosition: function()
{
if (self.pageYOffset) return self.pageYOffset; // Firefox, Chrome, Opera, Safari.
if (document.documentElement && document.documentElement.scrollTop) return document.documentElement.scrollTop; // Internet Explorer 6 (standards mode).
if (document.body.scrollTop) return document.body.scrollTop; // Internet Explorer 6, 7 and 8.
return 0; // None of the above.
},
viewportHeight: function()
{ return (document.compatMode === "CSS1Compat") ? document.documentElement.clientHeight : document.body.clientHeight; },
documentHeight: function()
{ return (document.height !== undefined) ? document.height : document.body.offsetHeight; },
documentMaximumScrollPosition: function()
{ return this.documentHeight() - this.viewportHeight(); },
elementVerticalClientPositionById: function(id)
{
var element = document.getElementById(id);
var rectangle = element.getBoundingClientRect();
return rectangle.top;
},
/**
* Animation tick.
*/
scrollVerticalTickToPosition: function(currentPosition, targetPosition)
{
var filter = 0.2;
var fps = 60;
var difference = parseFloat(targetPosition) - parseFloat(currentPosition);
// Snap, then stop if arrived.
var arrived = (Math.abs(difference) <= 0.5);
if (arrived)
{
// Apply target.
scrollTo(0.0, targetPosition);
return;
}
// Filtered position.
currentPosition = (parseFloat(currentPosition) * (1.0 - filter)) + (parseFloat(targetPosition) * filter);
// Apply target.
scrollTo(0.0, Math.round(currentPosition));
// Schedule next tick.
setTimeout("EPPZScrollTo.scrollVerticalTickToPosition("+currentPosition+", "+targetPosition+")", (1000 / fps));
},
/**
* For public use.
*
* @param id The id of the element to scroll to.
* @param padding Top padding to apply above element.
*/
scrollVerticalToElementById: function(id, padding)
{
var element = document.getElementById(id);
if (element == null)
{
console.warn('Cannot find element with id \''+id+'\'.');
return;
}
var targetPosition = this.documentVerticalScrollPosition() + this.elementVerticalClientPositionById(id) - padding;
var currentPosition = this.documentVerticalScrollPosition();
// Clamp.
var maximumScrollPosition = this.documentMaximumScrollPosition();
if (targetPosition > maximumScrollPosition) targetPosition = maximumScrollPosition;
// Start animation.
this.scrollVerticalTickToPosition(currentPosition, targetPosition);
}
};
回答by HarlemSquirrel
Here's a function that can include an optional offset for those fixed headers. No external libraries needed.
这是一个函数,可以为那些固定标头包含一个可选的偏移量。不需要外部库。
function scrollIntoView(selector, offset = 0) {
window.scroll(0, document.querySelector(selector).offsetTop - offset);
}
You can grab the height of an element using JQuery and scroll to it.
您可以使用 JQuery 获取元素的高度并滚动到它。
var headerHeight = $('.navbar-fixed-top').height();
scrollIntoView('#some-element', headerHeight)
Update March 2018
2018 年 3 月更新
Scroll to this answer without using JQuery
不使用 JQuery 滚动到这个答案
scrollIntoView('#answer-44786637', document.querySelector('.top-bar').offsetHeight)
回答by DAVID AJAYI
The best, shortest answer that what works even with animation effects:
最好,最短的答案,即使使用动画效果也能正常工作:
var scrollDiv = document.getElementById("myDiv").offsetTop;
window.scrollTo({ top: scrollDiv, behavior: 'smooth'});
If you have a fixed nav bar, just subtract its height from top value, so if your fixed bar height is 70px, line 2 will look like:
如果你有一个固定的导航栏,只需从顶部值减去它的高度,所以如果你的固定栏高度是 70px,第 2 行看起来像:
window.scrollTo({ top: scrollDiv-70, behavior: 'smooth'});
Explanation:Line 1 gets the element position
Line 2 scroll to element position; behavior
property adds a smooth animated effect
说明:第1行获取元素位置第2行滚动到元素位置;behavior
属性添加了平滑的动画效果
回答by ZhenyaUsenko
You can set focus to element. It works better than scrollIntoView
您可以将焦点设置为元素。它比scrollIntoView
node.setAttribute('tabindex', '-1')
node.setAttribute('tabindex', '-1')
node.focus()
node.focus()
node.removeAttribute('tabindex')
node.removeAttribute('tabindex')
回答by S M Kamran
Focus can be set on interactive elements only... Div only represent a logical section of the page.
焦点只能设置在交互元素上... Div 仅代表页面的逻辑部分。
Perhaps you can set the borders around div or change it's color to simulate a focus. And yes Visiblity is not focus.
也许您可以设置 div 周围的边框或更改其颜色以模拟焦点。是的,可见性不是焦点。