2016-04-07 8 views
2

アンカータグを使用する代わりにIDと一致する場合、データ属性を使用して要素をスクロールする方法を理解しようとしています。ここに私が働いているものがあります。データ属性を使用して要素にスクロール

ユーザーがボタンをクリックすると、コンテンツが表示され、データ属性に一致する特定の要素にスクロールします。私はそれが正しい選択をするためにIDに

<div class="container"> 
    <div class="post" data-id="content-one"> 
     post one 
    </div> 
    <div class="post" data-id="content-two"> 
     post two 
    </div> 
</div> 
<div class="container-two"> 
    <div id="content-one" class="post-content" > 
     content one 
    </div> 
    <div id="content-two" class="post-content" > 
     content two 
    </div> 
</div> 
$(".container .post").on('click', function() { 
    var data_id = $(this).data('id'); 
    $('.post-content').each(function() { 
     var el = $(this); 
     if (el.attr('id') == data_id) 
      el.show(); 
     else 
      el.hide(); 
    }); 
    $('html, body').animate({ 
     scrollTop: $(data_id).offset.top() 
    }, 'slow'); 
}); 

https://jsfiddle.net/clestcruz/vf4ufg6b/

答えて

6

を連結#をスクロールさせるように見えることはできません。 offset()は、要素の現在位置を含むオブジェクトを返す関数であるため、.offset().topを使用することもできます。次に、topキーを使用してアクセスできます。

$('html, body').animate({ 
    scrollTop: $('#' + data_id).offset().top 
}, 'slow'); 

DEMO

関連する問題