我试图将页面移动到<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';
我认为如果你添加一个标签到你的div,它将能够获得焦点:
<div class="divFirst" tabindex="-1">
</div>
我不认为它是有效的,虽然,tabindex只能应用于一个,区域,按钮,输入,对象,选择和文本区域。但不妨试一试。
你可以使用一个锚来“聚焦”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";
试试这个:
var divFirst = document.getElementById("divFirst");
divFirst.style.visibility = 'visible';
divFirst.style.display = 'block';
divFirst.tabIndex = "-1";
divFirst.focus();
如@:
http://jsfiddle.net/Vgrey/
要滚动到一个给定的元素,只做这个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);
}
};
scrollIntoView工作良好:
document.getElementById("divFirst").scrollIntoView();
MDN文档中的完整引用: https://developer.mozilla.org/en-US/docs/Web/API/Element.scrollIntoView
如果你想使用html,你可以使用这个:
a href="samplewebsite.com/subdivision.html#id
并将其作为指向特定元素id的HTML链接。它基本上是getElementById html版本。
试试这个函数
function navigate(divId) {
$j('html, body').animate({ scrollTop: $j("#"+divId).offset().top }, 1500);
}
传递div id作为参数,它将工作,我已经在使用它
在四处寻找之后,这是最后对我有用的方法:
找到/定位div在你的dom有滚动条。 对我来说,它看起来是这样的: "div class="table_body table_body_div" scroll_top="0" scroll_left="0" style="width: 1263px;身高:499 px;“ 我用这个xpath: //div[@class='table_body table_body_div'] 使用JavaScript像这样执行滚动: (JavascriptExecutor)司机).executeScript(“参数[0]。scrollLeft =参数[1];",元素,2000);
2000是我想向右滚动的像素数。 如果你想向下滚动div,使用scrollTop而不是scrollLeft。
注意:我尝试使用scrollIntoView,但它不能正常工作,因为我的网页有多个div。如果你只有一个集中注意力的主窗口,这是可行的。 如果你不想使用jQuery,这是我遇到的最好的解决方案。
下面是一个函数,它可以包含那些固定头的可选偏移量。不需要外部库。
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)
Chrome和Firefox
我一直在研究这个问题,我发现了这个问题,从某种程度上来说,这是最自然的方法。当然,这是我现在最喜欢的画卷。:)
const y = element.getBoundingClientRect().top + window.scrollY;
window.scroll({
top: y,
behavior: 'smooth'
});
IE、Edge和Safari的支持者
注意那个窗口。滚动({…options})在IE、Edge和Safari上不支持。在这种情况下,使用它可能是最好的 element.scrollIntoView()。(在IE 6上支持)。你很可能(读:未经测试)传入选项而没有任何副作用。
当然,这些可以被包装在一个函数中,根据所使用的浏览器来执行。
类似于@穴居人的解决方案
const element = document.getElementById('theelementsid');
if (element) {
window.scroll({
top: element.scrollTop,
behavior: 'smooth',
})
}
您可以将焦点设置为元素。它比scrollIntoView工作得更好
node。setAttribute(“tabindex”、“- 1”)
node.focus ()
node . removeAttribute(“tabindex”)
我经常使用滚动容器到其内容的方法。
/**
@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,浏览器。我通常使用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)
})
}
})();
最好的,最简短的回答是什么即使是动画效果也有效:
var scrollDiv = document.getElementById("myDiv").offsetTop;
window.scrollTo({ top: scrollDiv, behavior: 'smooth'});
如果你有一个固定的导航条,只需从顶部值中减去它的高度,所以如果你的固定导航条高度是70px,第2行将看起来像这样:
window.scrollTo({ top: scrollDiv-70, behavior: 'smooth'});
解释: 第1行获取元素位置 第2行滚动到元素位置;属性添加平滑的动画效果
我们可以通过3种方法来实现:
注意:
"automatic-scroll" =>特定元素
" scrolble -div" =>可滚动区域div
方法1:
document.querySelector('.automatic-scroll').scrollIntoView({
behavior: 'smooth'
});
方法2:
location.href = "#automatic-scroll";
方法3:
$('#scrollable-div').animate({
scrollTop: $('#automatic-scroll').offset().top - $('#scrollable-div').offset().top +
$('#scrollable-div').scrollTop()
})
重要注意:如果可滚动区域高度为“auto”,方法1和方法2将非常有用。方法3是有用的,如果我们使用滚动区域的高度,如“calc(100vh - 200px)”。
如果您只是想滚动到div中列表的底部,您可以这样做。
<body>
<div class="container">
<div class="box">1</div>
<div class="box">2</div>
<div class="box">3</div>
<div class="box">4</div>
<div class="box">5</div>
<div class="box">6</div>
<div class="box">7</div>
<div class="box">8</div>
<div class="box">9</div>
</div>
<button>Scroll To</button>
<script>
const btn = document.querySelector("button");
const container = document.querySelector(".container");
btn.addEventListener("click",()=>{
const toplast = document.querySelector(".container").lastElementChild;
toplast.scrollIntoView();
})
</script>
</body>
示例输出