2017-08-27 1 views
0

私は自分のページのスクロール水平部分を作成しようとしています。単一ページの水平スクロールアンカー(jQuery)

これはかなりシンプルなコンセプトです。以前は何度もやっていましたので、わかりやすいものが欠けているはずです。

クリックごとに正しいオフセットの間の選択肢のようです。

$('a.scroll-trigger').click(function(e) { 
 
    var $this = $(this); 
 
    var $anchor = $($this.attr('href')); 
 
    var $container = $($this.attr('data-container')); 
 
    var offset = $anchor.offset().left; 
 
    $container.scrollLeft(offset); 
 
    e.preventDefault(); 
 
});
#pages { 
 
    overflow-x: hidden; 
 
    white-space: nowrap; 
 
} 
 

 
#pages>section { 
 
    display: inline-block; 
 
    width: 768px; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 

 
<ul> 
 
    <li><a class="scroll-trigger" href="#section1" data-container="#pages">Section 1</a></li> 
 
    <li><a class="scroll-trigger" href="#section2" data-container="#pages">Section 2</a></li> 
 
    <li><a class="scroll-trigger" href="#section3" data-container="#pages">Section 3</a></li> 
 
</ul> 
 

 
<!-- pages is nested in a container with a maximum width of 768px. --> 
 
<div id="pages"> 
 
    <section id="section1"> 
 
    <h2>Section 1</h2> 
 
    </section> 
 
    <section id="section2"> 
 
    <h2>Section 2</h2> 
 
    </section> 
 
    <section id="section3"> 
 
    <h2>Section 3</h2> 
 
    </section> 
 
</div>

それは正常に動作していません。 offset変数が正しいとは限りません。

アイデア?

答えて

0

これはあなたが探しているものですか?

$('.scroll-trigger').each(function(index){ 
 
    $(this).on('click',function(e) { 
 
    var $this = $(this); 
 
    var $anchor = $this.attr('href'); 
 
    var $container = $this.attr('data-container'); 
 
    var elem = $($anchor); 
 
    var offset = (elem.offset().left - elem.offsetParent().offset().left); 
 

 
    if(offset >= 0){ 
 
     $($container).animate({'scrollLeft' : offset * index},200); 
 
    }else{ 
 
     $($container).animate({'scrollLeft' : offset * -index},200); 
 
    } 
 
    e.preventDefault(); 
 
    });      
 
})
#pages{ 
 
    position: relative; 
 
    overflow-x: hidden; 
 
    white-space: nowrap; 
 
    width: 100%; 
 
    border:1px solid #565656; 
 
} 
 
#pages>section { 
 
    display: inline-block; 
 
    width: 100%; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<ul> 
 
    <li><a class="scroll-trigger" href="#section1" data-container="#pages">Section 1</a></li> 
 
    <li><a class="scroll-trigger" href="#section2" data-container="#pages">Section 2</a></li> 
 
    <li><a class="scroll-trigger" href="#section3" data-container="#pages">Section 3</a></li> 
 
</ul> 
 

 
<!-- pages is nested in a container with a maximum width of 768px. --> 
 
<div id="pages"> 
 
    <section id="section1"> 
 
    <h2>Section 1</h2> 
 
    </section> 
 
    <section id="section2"> 
 
    <h2>Section 2</h2> 
 
    </section> 
 
    <section id="section3"> 
 
    <h2>Section 3</h2> 
 
    </section> 
 
</div>

関連する問題