简体   繁体   中英

Scroll to anchor within div of set height

I am hoping somebody can help me out with my Javascript. The JSFiddle shows you how far I have got, I'm not far off...but I am basically trying to get the content of the enclosed DIVs to align to the top of the '.news_window' box when the nav is clicked.

http://jsfiddle.net/s5sxa0sk/2/

I realise that the scrollTop going to 'this' is incorrect, but I don't know how else to proceed.

Any input would be very much appreciated.

The HTML:

<ul class="news_archive">
  <li class="active"><a href="#2014_dec">December</a></li>
  <li><a href="#2014_nov">November</a></li>
  <li><a href="#2014_oct">October</a></li>
</ul>

<div class="news_window">
  <div id="dec_2014">
    <p>December Content</p>
  </div>
  <div id="nov_2014">
    <p>November Content</p>
  </div>
  <div id="oct_2014">
    <p>October Content</p>
  </div>
</div>

The Javascript:

<script>
 $(".news_archive li").click(function(e){
     e.preventDefault();
     $('.news_window').animate({scrollTop:$(this).position().top}, 'slow');
     $('.news_archive li.active').removeClass('active');
     $(this).addClass('active');
});
</script>

Your main issues is you're using the #new_archive link's top position to animate the scroll instead of the #news_window item's top position. You need to find the #news_window element based on which link is clicked and use that element's position().top.

You will also need a wrapper around the #news_window items otherwise each element's position().top will change based on the current scroll position of the #news_window element. This wrapper will need position: relative set.

Here's what I mean:

<ul class="news_archive">
    <li class="active">
        <a data-id="dec_2014" href="#">December</a>
    </li>
    <li>
        <a data-id="nov_2014" href="#">November</a>
    </li>
    <li>
        <a data-id="oct_2014" href="#">October</a>
    </li>
</ul>

<div class="news_window">
    <div class="wrapper">
        <div id="dec_2014">
            <p>December Content</p>
        </div>
        <div id="nov_2014">
            <p>November Content</p>
        </div>
        <div id="oct_2014">
            <p>October Content</p>
        </div>
    </div>
</div>

And the Javascript:

$('.news_archive li a').click(function(e) {
    e.preventDefault();

    var newsWindowEl = $('#'+$(this).data('id'));

    $('.news_window').animate({
        scrollTop: newsWindowEl.position().top
    }, 'slow');

    $('.news_archive li.active').removeClass('active');
    $(this).parents('li').addClass('active');
 });

Here's a working version of your fiddle: http://jsfiddle.net/s5sxa0sk/42/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM