我正在尝试将页面移至某个<div>
元素。
我尝试下一个代码无济于事:
document.getElementById("divFirst").style.visibility = 'visible';
document.getElementById("divFirst").style.display = 'block';
我正在尝试将页面移至某个<div>
元素。
我尝试下一个代码无济于事:
document.getElementById("divFirst").style.visibility = 'visible';
document.getElementById("divFirst").style.display = 'block';
Answers:
您可以使用锚点来“聚焦” div。即:
<div id="myDiv"></div>
然后使用以下javascript:
// the next line is required to work around a bug in WebKit (Chrome / Safari)
location.href = "#";
location.href = "#myDiv";
location.href="#";location.href="#myDiv"
。使用id="myDiv"
是首选的,name="myDiv"
并且也可以使用。
scrollIntoView运作良好:
document.getElementById("divFirst").scrollIntoView();
MDN文档中的完整参考:https :
//developer.mozilla.org/zh-CN/docs/Web/API/Element.scrollIntoView
您的问题和答案看起来不同。我不知道我是否记错了,但是对于那些用谷歌搜索并到达此处的人,我的答案是:
我的回答说明:
这是一个简单的JavaScript
当您需要滚动屏幕到具有id =“ yourSpecificElementId”的元素时调用此方法
window.scroll(0,findPos(document.getElementById("yourSpecificElementId")));
即。对于上述问题,是否打算将屏幕滚动到ID为'divFirst'的div
该代码将是: window.scroll(0,findPos(document.getElementById("divFirst")));
并且您需要此功能才能工作:
//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];
}
}
屏幕将滚动到您的特定元素。
window
要滚动,则不要滚动查看区域
[curtop]
为curtop
结尾后即可工作
(window.screen.height/2)
从findPos中减去
我一直在研究这一点,并想出了一种感觉,这似乎是最自然的方式。当然,这是我个人现在最喜欢的滚动条。:)
const y = element.getBoundingClientRect().top + window.scrollY;
window.scroll({
top: y,
behavior: 'smooth'
});
请注意,window.scroll({ ...options })
IE,Edge和Safari不支持该功能。在这种情况下,最好使用
element.scrollIntoView()
。(在IE 6上受支持)。您很可能(未测试)通过了选项而没有任何副作用。
当然,这些可以包装在一个函数中,该函数的行为取决于所使用的浏览器。
window.scroll
试试这个:
var divFirst = document.getElementById("divFirst");
divFirst.style.visibility = 'visible';
divFirst.style.display = 'block';
divFirst.tabIndex = "-1";
divFirst.focus();
例如@:
element.tabIndex
但不是element.tabindex
;第二个可以在Firefox上运行,但不能在Chrome上运行(至少在我前一段时间尝试过的时候)。当然,作为一个HTML属性都tabIndex
与tabindex
工作(和XHTML,tabindex
必须使用)
要滚动到给定的元素,只需在下面制作此仅适用于javascript的解决方案即可。
简单用法:
EPPZScrollTo.scrollVerticalToElementById('signup_form', 20);
引擎对象(您可以摆弄滤镜,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);
}
};
这是一个可以为这些固定标头包含可选偏移量的函数。无需外部库。
function scrollIntoView(selector, offset = 0) {
window.scroll(0, document.querySelector(selector).offsetTop - offset);
}
您可以使用JQuery抓住元素的高度并滚动到它。
var headerHeight = $('.navbar-fixed-top').height();
scrollIntoView('#some-element', headerHeight)
2018年3月更新
滚动到此答案而不使用JQuery
scrollIntoView('#answer-44786637', document.querySelector('.top-bar').offsetHeight)
您可以将焦点设置为element。它比scrollIntoView
node.setAttribute('tabindex', '-1')
node.focus()
node.removeAttribute('tabindex')
最佳,最短的答案即使对动画效果也有效:
var scrollDiv = document.getElementById("myDiv").offsetTop;
window.scrollTo({ top: scrollDiv, behavior: 'smooth'});
如果您有固定的导航栏,只需从顶部值减去它的高度,所以如果您固定的导航栏高度为70px,则第2行将如下所示:
window.scrollTo({ top: scrollDiv-70, behavior: 'smooth'});
说明:
第1行获得元素位置第2行滚动到元素位置;behavior
属性添加了平滑的动画效果
我认为,如果将tabindex添加到div中,它将能够获得焦点:
<div class="divFirst" tabindex="-1">
</div>
我不认为这是有效的,tabindex只能应用于a,区域,按钮,输入,对象,选择和textarea。但是尝试一下。
tabindex
有一个“核心属性”,是“全局属性”(HTML语言中所有元素共有的属性)。参见w3.org/TR/2011/WD-html-markup-20110113/global-attributes.html
经过一番环顾后,这终于对我有用:
在具有滚动条的dom中查找/定位div。对我来说,它看起来像这样:“ div class =” table_body table_body_div“ scroll_top =” 0“ scroll_left =” 0“ style =” width:1263px; 高度:499像素;”
我通过以下xpath找到了它:// div [@ class ='table_body table_body_div']
使用JavaScript执行这样的滚动:(JavascriptExecutor)驱动程序).executeScript(“ arguments [0] .scrollLeft = arguments [1];”,element,2000);
2000是我想向右滚动的像素数。如果要向下滚动div,请使用scrollTop而不是scrollLeft。
注意:我尝试使用scrollIntoView,但由于我的网页有多个div,因此无法正常工作。如果只有一个主窗口位于焦点上,它将起作用。如果您不想使用我不想使用的jQuery,这是我遇到的最好的解决方案。
我经常使用的一种方法来将容器滚动到其内容。
/**
@param {HTMLElement} container : element scrolled.
@param {HTMLElement} target : element where to scroll.
@param {number} [offset] : scroll back by offset
*/
var scrollAt=function(container,target,offset){
if(container.contains(target)){
var ofs=[0,0];
var tmp=target;
while (tmp!==container) {
ofs[0]+=tmp.offsetWidth;
ofs[1]+=tmp.offsetHeight;
tmp=tmp.parentNode;
}
container.scrollTop = Math.max(0,ofs[1]-(typeof(offset)==='number'?offset:0));
}else{
throw('scrollAt Error: target not found in container');
}
};
如果您希望全局覆盖,也可以执行以下操作:
HTMLElement.prototype.scrollAt=function(target,offset){
if(this.contains(target)){
var ofs=[0,0];
var tmp=target;
while (tmp!==this) {
ofs[0]+=tmp.offsetWidth;
ofs[1]+=tmp.offsetHeight;
tmp=tmp.parentNode;
}
container.scrollTop = Math.max(0,ofs[1]-(typeof(offset)==='number'?offset:0));
}else{
throw('scrollAt Error: target not found in container');
}
};
由于行为原因,“平滑”在Safari,Safari ios,Explorer中不起作用。我通常使用requestAnimationFrame编写一个简单的函数
(function(){
var start;
var startPos = 0;
//Navigation scroll page to element
function scrollTo(timestamp, targetTop){
if(!start) start = timestamp
var runtime = timestamp - start
var progress = Math.min(runtime / 700, 1)
window.scroll(0, startPos + (targetTop * progress) )
if(progress >= 1){
return;
}else {
requestAnimationFrame(function(timestamp){
scrollTo(timestamp, targetTop)
})
}
};
navElement.addEventListener('click', function(e){
var target = e.target //or this
var targetTop = _(target).getBoundingClientRect().top
startPos = window.scrollY
requestAnimationFrame(function(timestamp){
scrollTo(timestamp, targetTop)
})
}
})();
visibility
并且display
用于使元素(不可见)可见。您要在屏幕上滚动div吗?