Estou tentando mover a página para um <div>elemento.
Eu tentei o próximo código sem sucesso:
document.getElementById("divFirst").style.visibility = 'visible';
document.getElementById("divFirst").style.display = 'block';
Estou tentando mover a página para um <div>elemento.
Eu tentei o próximo código sem sucesso:
document.getElementById("divFirst").style.visibility = 'visible';
document.getElementById("divFirst").style.display = 'block';
Respostas:
Você pode usar uma âncora para "focalizar" a div. Ou seja:
<div id="myDiv"></div>
e use o seguinte 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"É preferível usar name="myDiv"e também funciona.
scrollIntoView funciona bem:
document.getElementById("divFirst").scrollIntoView();
referência completa nos documentos MDN:
https://developer.mozilla.org/en-US/docs/Web/API/Element.scrollIntoView
scrollIntoView
sua pergunta e as respostas parecem diferentes. Não sei se estou enganado, mas para aqueles que pesquisam e chegam aqui, minha resposta seria a seguinte:
Minha resposta explicou:
aqui está um javascript simples para isso
chame isso quando precisar rolar a tela para um elemento que tenha id = "yourSpecificElementId"
window.scroll(0,findPos(document.getElementById("yourSpecificElementId")));
ie para a pergunta acima, se a intenção é rolar a tela para a div com o ID 'divFirst'
o código seria: window.scroll(0,findPos(document.getElementById("divFirst")));
e você precisa desta função para o trabalho:
//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];
}
}
a tela será rolada para o seu elemento específico.
windowque você gostaria de se deslocar, não é uma área de visualização-ing estouro
[curtop]para curtopno final
(window.screen.height/2)de findPos
Eu estive analisando um pouco isso e descobri um que parece ser a maneira mais natural de fazer isso. Claro, este é o meu pergaminho favorito agora. :)
const y = element.getBoundingClientRect().top + window.scrollY;
window.scroll({
top: y,
behavior: 'smooth'
});
Observe que window.scroll({ ...options })não há suporte no IE, Edge e Safari. Nesse caso, é mais provável que seja melhor usar
element.scrollIntoView(). (Suportado no IE 6). Você pode provavelmente (ler: não testado) passar opções sem nenhum efeito colateral.
É claro que eles podem ser agrupados em uma função que se comporta de acordo com o navegador que está sendo usado.
window.scroll
Tente o seguinte:
var divFirst = document.getElementById("divFirst");
divFirst.style.visibility = 'visible';
divFirst.style.display = 'block';
divFirst.tabIndex = "-1";
divFirst.focus();
por exemplo @:
element.tabIndexmas não element.tabindex; o segundo funciona no Firefox, mas não no Chrome (pelo menos quando tentei há algum tempo). Claro, usado como um atributo HTML tanto tabIndexe tabindextrabalho (e em XHTML, tabindexdeve ser utilizado)
Para rolar para um determinado elemento, criei esta solução apenas em javascript abaixo.
Uso simples:
EPPZScrollTo.scrollVerticalToElementById('signup_form', 20);
Objeto do mecanismo (você pode mexer no filtro, nos valores de 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);
}
};
Aqui está uma função que pode incluir um deslocamento opcional para esses cabeçalhos fixos. Nenhuma biblioteca externa é necessária.
function scrollIntoView(selector, offset = 0) {
window.scroll(0, document.querySelector(selector).offsetTop - offset);
}
Você pode pegar a altura de um elemento usando JQuery e rolar para ele.
var headerHeight = $('.navbar-fixed-top').height();
scrollIntoView('#some-element', headerHeight)
Atualização março de 2018
Role até esta resposta sem usar o JQuery
scrollIntoView('#answer-44786637', document.querySelector('.top-bar').offsetHeight)
Você pode definir o foco como elemento. Funciona melhor quescrollIntoView
node.setAttribute('tabindex', '-1')
node.focus()
node.removeAttribute('tabindex')
A melhor e mais curta resposta que funciona mesmo com efeitos de animação:
var scrollDiv = document.getElementById("myDiv").offsetTop;
window.scrollTo({ top: scrollDiv, behavior: 'smooth'});
Se você tiver uma barra de navegação fixa, basta subtrair a altura do valor superior. Portanto, se a altura da barra fixa for 70 px, a linha 2 será semelhante a:
window.scrollTo({ top: scrollDiv-70, behavior: 'smooth'});
Explicação: A
linha 1 faz com que a posição do elemento role a linha 2 para a posição do elemento; behaviorA propriedade adiciona um efeito animado suave
Eu acho que se você adicionar um tabindex ao seu div, ele será capaz de obter foco:
<div class="divFirst" tabindex="-1">
</div>
Porém, não acho que seja válido, o tabindex pode ser aplicado apenas a uma área, botão, entrada, objeto, seleção e área de texto. Mas dá-lhe uma chance.
tabindexhá um "atributo principal", que é "atributos globais" (atributos comuns a todos os elementos na linguagem HTML). Consulte w3.org/TR/2011/WD-html-markup-20110113/global-attributes.html
Semelhante à solução de @ caveman
const element = document.getElementById('theelementsid');
if (element) {
window.scroll({
top: element.scrollTop,
behavior: 'smooth',
})
}
Você não pode se concentrar em uma div. Você pode focar apenas em um elemento de entrada nessa div. Além disso, você precisa usar element.focus () em vez de display ()
<div>foco se estiver usando o tabindexatributo Veja dev.w3.org/html5/spec-author-view/editing.html#attr-tabindex
Depois de olhar muito ao redor, foi o que finalmente funcionou para mim:
Encontre / localize div em seu domínio, que possui barra de rolagem. Para mim, ficou assim: "div class =" table_body table_body_div "scroll_top =" 0 "scroll_left =" 0 "style =" width: 1263px; altura: 499px; "
Eu o localizei com este xpath: // div [@ class = 'table_body table_body_div']
Utilizava JavaScript para executar rolagem como esta: driver (JavascriptExecutor)) .executeScript ("argumentos [0] .scrollLeft = argumentos [1];", elemento, 2000);
2000 é o número de pixels que eu queria rolar para a direita. Use scrollTop em vez de scrollLeft se desejar rolar sua div para baixo.
Nota: Tentei usar o scrollIntoView, mas não funcionou corretamente porque minha página da web tinha vários divs. Funcionará se você tiver apenas uma janela principal onde o foco está. Esta é a melhor solução que encontrei se você não quiser usar o jQuery que eu não queria.
Um método que costumo usar para rolar um contêiner para o seu conteúdo.
/**
@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');
}
};
se você deseja substituir globalmente, também pode:
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');
}
};
Devido ao comportamento "suave" não funciona no Safari, Safari ios, Explorer. Normalmente, escrevo uma função simples utilizando 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)
})
}
})();
tente esta função
function navigate(divId) {
$j('html, body').animate({ scrollTop: $j("#"+divId).offset().top }, 1500);
}
Passe o div id como parâmetro ele vai funcionar já estou usando ele
$j?
visibilityedisplaysão usados para tornar os elementos (in) visíveis. Deseja rolar a div na tela?