ページを<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 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/en-US/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。2つ目は、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)
要素にフォーカスを設定できます。それはよりよく機能します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プロパティは滑らかなアニメーション効果を追加します
divにtabindexを追加すると、フォーカスを取得できると思います。
<div class="divFirst" tabindex="-1">
</div>
有効ではないと思いますが、tabindexは、エリア、ボタン、入力、オブジェクト、選択、およびテキストエリアにのみ適用できます。しかし、それを試してみてください。
tabindexは「コア属性」があり、これは「グローバル属性」(HTML言語のすべての要素に共通の属性)です。w3.org/TR/2011/WD-html-markup-20110113/global-attributes.htmlを
@cavemanのソリューションに似ています
const element = document.getElementById('theelementsid');
if (element) {
window.scroll({
top: element.scrollTop,
behavior: 'smooth',
})
}
あなたはdivに集中することはできません。そのdiv内の入力要素にのみ焦点を当てることができます。また、display()の代わりにelement.focus()を使用する必要があります
<div>を使用すると、フォーカス可能にすることができtabindexます。dev.w3.org/html5/spec-author-view/editing.html#attr-tabindex
たくさん見回した後、これは最終的に私のために働いたものです:
スクロールバーのあるdomでdivを見つけます。私にとっては、このように見えました: "div class =" table_body table_body_div "scroll_top =" 0 "scroll_left =" 0 "style =" width:1263px; 高さ:499px; "
私はこのxpathでそれを見つけました:// div [@ class = 'table_body table_body_div']
JavaScriptを使用して次のようにスクロールを実行します:(JavascriptExecutor)driver).executeScript( "arguments [0] .scrollLeft = arguments [1];"、element、2000);
2000は、右にスクロールしたいピクセル数です。divを下にスクロールする場合は、scrollLeftではなくscrollTopを使用します。
注:scrollIntoViewを使用しようとしましたが、私のWebページに複数のdivがあるため、正しく機能しませんでした。フォーカスがあるメインウィンドウが1つしかない場合に機能します。これは、私が使いたくない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)
})
}
})();
この機能を試してください
function navigate(divId) {
$j('html, body').animate({ scrollTop: $j("#"+divId).offset().top }, 1500);
}
div idをパラメーターとして渡し、機能します。すでに使用しています。
$j出身ですか?
visibilityそしてdisplay要素(で)目に見えるを作るために使用されます。画面でdivをスクロールしますか?