Sayfayı bir <div>öğeye taşımaya çalışıyorum .
Ben boşuna sonraki kodu denedim:
document.getElementById("divFirst").style.visibility = 'visible';
document.getElementById("divFirst").style.display = 'block';
Sayfayı bir <div>öğeye taşımaya çalışıyorum .
Ben boşuna sonraki kodu denedim:
document.getElementById("divFirst").style.visibility = 'visible';
document.getElementById("divFirst").style.display = 'block';
Yanıtlar:
Div "odaklamak" için bir çapa kullanabilirsiniz. yani:
<div id="myDiv"></div>
ve aşağıdaki javascript'i kullanın:
// the next line is required to work around a bug in WebKit (Chrome / Safari)
location.href = "#";
location.href = "#myDiv";
location.href="#";location.href="#myDiv". Kullanmak id="myDiv"tercih edilir name="myDiv"ve çok işe yarar.
scrollIntoView iyi çalışır:
document.getElementById("divFirst").scrollIntoView();
MDN belgelerinde tam referans:
https://developer.mozilla.org/en-US/docs/Web/API/Element.scrollIntoView
Sorunuz ve cevaplarınız farklı görünüyor. Yanlış olup olmadığımı bilmiyorum, ancak googles ve buraya ulaşanlar için cevabım şöyle olurdu:
Cevabım açıkladı:
İşte bunun için basit bir javascript
ekranı id = "yourSpecificElementId" olan bir öğeye kaydırmanız gerektiğinde bunu çağırın
window.scroll(0,findPos(document.getElementById("yourSpecificElementId")));
yani. yukarıdaki soru için, eğer amaç 'divFirst' kimliğine sahip ekranı div'e kaydırmaksa
kod şöyle olur: window.scroll(0,findPos(document.getElementById("divFirst")));
ve çalışma için bu fonksiyona ihtiyacınız var:
//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];
}
}
ekran özel öğenize kaydırılacaktır.
windowtaşmak istediğiniz bir görüntüleme alanı değil, kaydırmak istiyorsanız
[curtop]hiç curtopsonunda
(window.screen.height/2), findPos
Biraz buna bakıyordum ve bunu bir şekilde yapmanın en doğal yolu gibi hissettiğini anladım. Tabii ki, bu benim kişisel favorim. :)
const y = element.getBoundingClientRect().top + window.scrollY;
window.scroll({
top: y,
behavior: 'smooth'
});
window.scroll({ ...options })IE, Edge ve Safari'de desteklenmediğini unutmayın . Bu durumda, muhtemelen en iyisi kullanmaktır
element.scrollIntoView(). (IE 6'da desteklenir). Şunları yapabilirsiniz Büyük olasılıkla hiçbir yan etkisi olmadan seçenekleri geçmek: (denenmemiş okuyun).
Bunlar elbette hangi tarayıcının kullanıldığına göre davranan bir fonksiyona sarılabilir.
window.scroll
Bunu dene:
var divFirst = document.getElementById("divFirst");
divFirst.style.visibility = 'visible';
divFirst.style.display = 'block';
divFirst.tabIndex = "-1";
divFirst.focus();
Örneğin @:
element.tabIndexama değil element.tabindex; ikincisi Firefox'ta çalışıyor ancak Chrome'da çalışmıyor (en azından bir süre önce denediğimde). Tabii ki, bir HTML niteliği her iki olarak kullanılan tabIndexve tabindexişin (ve XHTML üzerine, tabindexkullanılmalıdır)
Belirli bir öğeye ilerlemek için aşağıdaki javascript çözümünü aşağıda yaptık.
Basit kullanım:
EPPZScrollTo.scrollVerticalToElementById('signup_form', 20);
Motor nesnesi (filtre, fps değerleri ile hareket edebilirsiniz):
/**
*
* 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);
}
};
İşte bu sabit başlıklar için isteğe bağlı bir ofset içerebilen bir işlev. Harici kütüphaneye gerek yok.
function scrollIntoView(selector, offset = 0) {
window.scroll(0, document.querySelector(selector).offsetTop - offset);
}
JQuery kullanarak bir öğenin yüksekliğini yakalayabilir ve öğeye ilerleyebilirsiniz.
var headerHeight = $('.navbar-fixed-top').height();
scrollIntoView('#some-element', headerHeight)
Mart 2018 Güncellemesi
JQuery kullanmadan bu cevaba ilerleyin
scrollIntoView('#answer-44786637', document.querySelector('.top-bar').offsetHeight)
Odağı öğeye ayarlayabilirsiniz. Daha iyi çalışırscrollIntoView
node.setAttribute('tabindex', '-1')
node.focus()
node.removeAttribute('tabindex')
Animasyon efektlerinde bile işe yarayan en iyi, en kısa cevap:
var scrollDiv = document.getElementById("myDiv").offsetTop;
window.scrollTo({ top: scrollDiv, behavior: 'smooth'});
Sabit bir gezinme çubuğunuz varsa, yüksekliğini en yüksek değerden çıkarın, böylece sabit çubuk yüksekliğiniz 70 piksel ise, satır 2 aşağıdaki gibi görünecektir:
window.scrollTo({ top: scrollDiv-70, behavior: 'smooth'});
Açıklama:
Satır 1, eleman konumu Satır 2'yi eleman konumuna kaydırır; behaviorözelliği yumuşak bir animasyon efekti ekler
Div'inize bir tabindex eklerseniz, odaklanabileceğinizi düşünüyorum:
<div class="divFirst" tabindex="-1">
</div>
Tabindex sadece bir, alan, düğme, giriş, nesne, seçim ve metin alanına uygulanabilir olduğunu düşünmüyorum. Ama bir deneyin.
tabindex"genel özellikler" olan bir "çekirdek özellik" tir (HTML dilindeki tüm öğeler için ortak olan özellikler). Bkz. W3.org/TR/2011/WD-html-markup-20110113/global-attributes.html
@ Caveman's Solution benzer
const element = document.getElementById('theelementsid');
if (element) {
window.scroll({
top: element.scrollTop,
behavior: 'smooth',
})
}
Bir div'a odaklanamazsınız. Yalnızca bu div'deki bir giriş öğesine odaklanabilirsiniz. Ayrıca, display () yerine element.focus () öğesini kullanmanız gerekir
<div>kullanıyorsanız odaklanabilir hale getirebilirsiniz tabindex. Bkz. Dev.w3.org/html5/spec-author-view/editing.html#attr-tabindex
Çok etrafına baktıktan sonra nihayet benim için işe yaradı:
Domunuzda kaydırma çubuğuna sahip div öğesini bulun / bulun. Benim için şöyle görünüyordu: "div class =" table_body table_body_div "scroll_top =" 0 "scroll_left =" 0 "style =" width: 1263px; yükseklik: 499 piksel; "
Bu xpath ile buldum: // div [@ class = 'table_body table_body_div']
Kaydırma işlemini aşağıdaki gibi yürütmek için JavaScript kullanıldı: (JavascriptExecutor) sürücü) .executeScript ("arguments [0] .scrollLeft = arguments [1];", element, 2000);
2000 sağa kaydırmak istediğim piksel sayısı. Div'inizi aşağı kaydırmak istiyorsanız scrollLeft yerine scrollTop komutunu kullanın.
Not: scrollIntoView kullanmayı denedim, ancak web sayfamın birden fazla div olduğu için düzgün çalışmadı. Odaklanmanın bulunduğu tek bir ana pencereniz varsa çalışır. Bu, istemediğim jQuery kullanmak istemiyorsanız karşılaştığım en iyi çözümdür.
Bir kapsayıcıyı içeriğine kaydırmak için sık kullandığım yöntem.
/**
@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');
}
};
global olarak geçersiz kılma isteğiniz varsa şunları da yapabilirsiniz:
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');
}
};
Davranış nedeniyle "pürüzsüz" Safari, Safari ios, Explorer'da çalışmıyor. Genellikle requestAnimationFrame kullanarak basit bir işlev yazıyorum
(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)
})
}
})();
bu işlevi dene
function navigate(divId) {
$j('html, body').animate({ scrollTop: $j("#"+divId).offset().top }, 1500);
}
Çalışacağım parametre olarak div kimliğini iletiyorum Zaten kullanıyorum
$jgeliyor?
visibilityvedisplayöğeleri (in) görünür yapmak için kullanılır. Ekranda div'i kaydırmak ister misiniz?