2009-03-11 9 views
76

私はスクロールdivを持っていて、クリックするとリンクがありたいので、これを強制的にスクロールして要素を表示します。私はこのようにそのJavasSriptを書いた :div内の要素にスクロールする方法は?

document.getElementById(chr).scrollIntoView(true); 

が、div自体をスクロールしながら、これは、すべてのページをスクロールします。 これを修正するには?

私はあなたがにスクロールしたいDIV内の要素の位置を見つける必要があり、かつscrollTopスプライトプロパティを設定することを

MyContainerDiv.getElementById(chr).scrollIntoView(true); 
+0

scrollTopスプライトは必ずしもない私を務めているものである:そして、ここでは、使用のいくつかの例であり、使用可能な値を返します。私は '$(document).ready({}) '関数で' SetTimeout'を使い、スクロールしたい要素に 'focus()'を設定する傾向があります。私のための作品 – DerpyNerd

答えて

211

、その親(スクロールするdivコンテナ)に対して相対的に:

var myElement = document.getElementById('element_within_div'); 
var topPos = myElement.offsetTop; 

変数topPosは、スクロールするdivの上部と表示させたい要素(ピクセル単位)の間の距離に設定されるようになりました。

は、今、私たちはscrollTopを使用して、その位置にスクロールするdiv要素を伝える:

document.getElementById('scrolling_div').scrollTop = topPos; 

あなたはプロトタイプのJSフレームワークを使用している場合は、あなたがこのように同じことをしたい:

var posArray = $('element_within_div').positionedOffset(); 
$('scrolling_div').scrollTop = posArray[1]; 

これも、divをスクロールして、表示したい要素が一番上になるようにします(そうでない場合は、できるだけ下にスクロールして表示されます)。

+6

これは本当に役立った!スクロールを複数回設定する場合は、現在のスクロール位置でオフセットする必要があります。 jQueryの使い方は次のとおりです: $( '#scrolling_div')。scrollTop($( '#scrolling_div')。scrollTop()+ $( '#element_within_div')。 – DenimChicken

+0

はもう動作しません。offsetTopは常に0になります – singe3

+2

myElement.offsetTopをリクエストすると、パフォーマンスのボトルネックとなるリフロー(レイアウトのスラッシング)が発生することに注意してください(https://developers.google.com/web/ hl = en#回避レイアウトスラッシング) – Kestutis

56

のようにそれを言いたいです。

divElem.scrollTop = 0; 

更新

サンプルコードが上下に移動する

あなたがビューにスクロールしたい要素のオフセットトップを取得する必要があります
function move_up() { 
    document.getElementById('divElem').scrollTop += 10; 
    } 

    function move_down() { 
    document.getElementById('divElem').scrollTop -= 10; 
    } 
+2

私は特定の値でスクロールしていないことを確認するには、ビューをスクロールしたい –

7

コードは次のようになります。

var divElem = document.getElementById('scrolling_div'); 
var chElem = document.getElementById('element_within_div'); 
var topPos = divElem.offsetTop; 
divElem.scrollTop = topPos - chElem.offsetTop; 

あなたは子供のトップ位置とのdivのトップ位置との差をスクロールしたいです。

使用して、子要素へのアクセスを取得します。

var divElem = document.getElementById('scrolling_div'); 
var numChildren = divElem.childNodes.length; 

をというように....

+1

2行目は実際に 'var chElem = document.getElementById( 'element_within_div');を読んではいけません.3行目は' var topPos = divElem.offsetTop; 'を読みますか? – jayp

0

ユーザーアニメーションスクロール

はここで、プログラムで水平に<div>をスクロールする方法の例ですなし。JQuery。垂直方向にスクロールするには、scrollLeftへのJavaScriptの書き込みをscrollTopに置き換えます。

JSFiddle

https://jsfiddle.net/fNPvf/38536/

HTML

<!-- Left Button. --> 
<div style="float:left;"> 
    <!-- (1) Whilst it's pressed, increment the scroll. When we release, clear the timer to stop recursive scroll calls. --> 
    <input type="button" value="«" style="height: 100px;" onmousedown="scroll('scroller',3, 10);" onmouseup="clearTimeout(TIMER_SCROLL);"/> 
</div> 
<!-- Contents to scroll. --> 
<div id="scroller" style="float: left; width: 100px; height: 100px; overflow: hidden;"> 
    <!-- <3 --> 
    <img src="https://cdn.sstatic.net/Sites/stackoverflow/company/img/logos/so/so-logo.png?v=9c558ec15d8a" alt="image large" style="height: 100px" /> 
</div> 
<!-- Right Button. --> 
<div style="float:left;"> 
    <!-- As (1). (Use a negative value of 'd' to decrease the scroll.) --> 
    <input type="button" value="»" style="height: 100px;" onmousedown="scroll('scroller',-3, 10);" onmouseup="clearTimeout(TIMER_SCROLL);"/> 
</div> 

はJavaScript

// Declare the Shared Timer. 
var TIMER_SCROLL; 
/** 
Scroll function. 
@param id Unique id of element to scroll. 
@param d Amount of pixels to scroll per sleep. 
@param del Size of the sleep (ms).*/ 
function scroll(id, d, del){ 
    // Scroll the element. 
    document.getElementById(id).scrollLeft += d; 
    // Perform a delay before recursing this function again. 
    TIMER_SCROLL = setTimeout("scroll('"+id+"',"+d+", "+del+");", del); 
} 

信用度はDuxです。


オートアニメーションスクロール

また、ここでは左右に完全に<div>をスクロールするための機能があります。ここで変更するのは、スクロールの完全な拡張が、スクロールの再帰呼び出しを行う前に利用されているかどうかを確認することです。

JSFiddle

https://jsfiddle.net/0nLc2fhh/1/

HTML

<!-- Left Button. --> 
<div style="float:left;"> 
    <!-- (1) Whilst it's pressed, increment the scroll. When we release, clear the timer to stop recursive scroll calls. --> 
    <input type="button" value="«" style="height: 100px;" onclick="scrollFullyLeft('scroller',3, 10);"/> 
</div> 
<!-- Contents to scroll. --> 
<div id="scroller" style="float: left; width: 100px; height: 100px; overflow: hidden;"> 
    <!-- <3 --> 
    <img src="https://cdn.sstatic.net/Sites/stackoverflow/company/img/logos/so/so-logo.png?v=9c558ec15d8a" alt="image large" style="height: 100px" /> 
</div> 
<!-- Right Button. --> 
<div style="float:left;"> 
    <!-- As (1). (Use a negative value of 'd' to decrease the scroll.) --> 
    <input type="button" value="»" style="height: 100px;" onclick="scrollFullyRight('scroller',3, 10);"/> 
</div> 

はJavaScript

// Declare the Shared Timer. 
var TIMER_SCROLL; 
/** 
Scroll fully left function; completely scrolls a <div> to the left, as far as it will go. 
@param id Unique id of element to scroll. 
@param d Amount of pixels to scroll per sleep. 
@param del Size of the sleep (ms).*/ 
function scrollFullyLeft(id, d, del){ 
    // Fetch the element. 
    var el = document.getElementById(id); 
    // Scroll the element. 
    el.scrollLeft += d; 
    // Have we not finished scrolling yet? 
    if(el.scrollLeft < (el.scrollWidth - el.clientWidth)) { 
     TIMER_SCROLL = setTimeout("scrollFullyLeft('"+id+"',"+d+", "+del+");", del); 
    } 
} 

/** 
Scroll fully right function; completely scrolls a <div> to the right, as far as it will go. 
@param id Unique id of element to scroll. 
@param d Amount of pixels to scroll per sleep. 
@param del Size of the sleep (ms).*/ 
function scrollFullyRight(id, d, del){ 
    // Fetch the element. 
    var el = document.getElementById(id); 
    // Scroll the element. 
    el.scrollLeft -= d; 
    // Have we not finished scrolling yet? 
    if(el.scrollLeft > 0) { 
     TIMER_SCROLL = setTimeout("scrollFullyRight('"+id+"',"+d+", "+del+");", del); 
    } 
} 
2

あなたはjQueryのを使用している場合は、以下を使用したアニメーションでスクロールすることができます:

$(MyContainerDiv).animate({scrollTop: $(MyContainerDiv).scrollTop() + ($('element_within_div').offset().top - $(MyContainerDiv).offset().top)}); 

アニメーションはオプションです:あなたはまた、上で計算しscrollTopスプライト値を取り、コンテナのscrollTopプロパティに直接それを置くことができます。

2

必要な場合にのみ、あなたはこのscrollIfNeeded機能を使用することができ、div要素のビューに要素をスクロールする:

function scrollIfNeeded(element, container) { 
 
    if (element.offsetTop < container.scrollTop) { 
 
    container.scrollTop = element.offsetTop; 
 
    } else { 
 
    const offsetBottom = element.offsetTop + element.offsetHeight; 
 
    const scrollBottom = container.scrollTop + container.offsetHeight; 
 
    if (offsetBottom > scrollBottom) { 
 
     container.scrollTop = offsetBottom - container.offsetHeight; 
 
    } 
 
    } 
 
} 
 

 
document.getElementById('btn').addEventListener('click', ev => { 
 
    ev.preventDefault(); 
 
    scrollIfNeeded(document.getElementById('goose'), document.getElementById('container')); 
 
});
.scrollContainer { 
 
    overflow-y: auto; 
 
    max-height: 100px; 
 
    position: relative; 
 
    border: 1px solid red; 
 
    width: 120px; 
 
} 
 

 
body { 
 
    padding: 10px; 
 
} 
 

 
.box { 
 
    margin: 5px; 
 
    background-color: yellow; 
 
    height: 25px; 
 
    display: flex; 
 
    align-items: center; 
 
    justify-content: center; 
 
} 
 

 
#goose { 
 
    background-color: lime; 
 
}
<div id="container" class="scrollContainer"> 
 
    <div class="box">duck</div> 
 
    <div class="box">duck</div> 
 
    <div class="box">duck</div> 
 
    <div class="box">duck</div> 
 
    <div class="box">duck</div> 
 
    <div class="box">duck</div> 
 
    <div class="box">duck</div> 
 
    <div class="box">duck</div> 
 
    <div id="goose" class="box">goose</div> 
 
    <div class="box">duck</div> 
 
    <div class="box">duck</div> 
 
    <div class="box">duck</div> 
 
    <div class="box">duck</div> 
 
</div> 
 

 
<button id="btn">scroll to goose</button>

0

をここでは、目標数のために働くの単純な純粋なJavaScriptのソリューションです(scrollTopの値)、ターゲットDOM要素、またはいくつかの特別なStringの場合:

/** 
* target - target to scroll to (DOM element, scrollTop Number, 'top', or 'bottom' 
* containerEl - DOM element for the container with scrollbars 
*/ 
var scrollToTarget = function(target, containerEl) { 
    // Moved up here for readability: 
    var isElement = target && target.nodeType === 1, 
     isNumber = Object.prototype.toString.call(target) === '[object Number]'; 

    if (isElement) { 
     containerEl.scrollTop = target.offsetTop; 
    } else if (isNumber) { 
     containerEl.scrollTop = target; 
    } else if (target === 'bottom') { 
     containerEl.scrollTop = containerEl.scrollHeight - containerEl.offsetHeight; 
    } else if (target === 'top') { 
     containerEl.scrollTop = 0; 
    } 
}; 
// Scroll to the top 
var scrollableDiv = document.getElementById('scrollable_div'); 
scrollToTarget('top', scrollableDiv); 

または

// Scroll to 200px from the top 
var scrollableDiv = document.getElementById('scrollable_div'); 
scrollToTarget(200, scrollableDiv); 

または

// Scroll to targetElement 
var scrollableDiv = document.getElementById('scrollable_div'); 
var targetElement= document.getElementById('target_element'); 
scrollToTarget(targetElement, scrollableDiv); 
0

これが最終的に

/** Set parent scroll to show element 
* @param element {object} The HTML object to show 
* @param parent {object} The HTML object where the element is shown */ 
var scrollToView = function(element, parent) { 
    //Algorithm: Accumulate the height of the previous elements and add half the height of the parent 
    var offsetAccumulator = 0; 
    parent = $(parent); 
    parent.children().each(function() { 
     if(this == element) { 
      return false; //brake each loop 
     } 
     offsetAccumulator += $(this).innerHeight(); 
    }); 
    parent.scrollTop(offsetAccumulator - parent.innerHeight()/2); 
} 
関連する問題