简体   繁体   中英

Scroll to a element onClick JavaScript

So my HTML looks like this :

<section id="nav-wrapper">
  <div class="container">
    <ul id="ul-main_wrapper">
      <li class="item_1""></li>
      <li class="item_2"></li>
      <li class="item_3"></li>
      <li class="item_4"></li>
      <li class="item_5"></li>
      <li class="item_6"></li>
      <li class="item_7"></li>
      <li class="item_8"></li>
      <li class="item_9"></li>
      <li class="item_10"></li>
      <li class="close_clear">Back</li>
    </ul>
  </div>
</section>

I have a list that sits all onto one line so the CSS looks like :

#nav-wrapper {
    width: 100%!important;
    height: auto!important;
    white-space: nowrap;
    -webkit-overflow-scrolling: touch;
    overflow-x: scroll;
    bottom: 80px;
}

#ul-main_wrapper li {
    height: 20px;
    width: 20px;
    margin: 2px;
    display: inline-block;
}

onClick of the last item in the list that is back i'm trying to get the list to scroll back to the first item. But can't find anything that works.

EDIT :

Here's a JSFiddle : https://jsfiddle.net/svuh0mvj/1/

Just use scrollTop():

$('.close_clear').on('click', function() {
    $(window).scrollTop($('.item_1').offset().top);
})

DEMO

Or with animate:

$('.close_clear').on('click', function() {
    var body = $("html, body");
    body.stop().animate({scrollTop:$('.item_1').offset().top}, '500');
})

DEMO

To scroll to the left within your #nav-header div, use:

$('.close_clear').on('click', function() {
    var nav = $("#nav-wrapper");
    nav.animate({scrollLeft: $('.item_1').offset().left}, '500');
})

DEMO

If you are not using jquery, or don't want to use it, you could try to use .scrollIntoView()

MSDN: https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView

"The Element.scrollIntoView() method scrolls the current element into the visible area of the browser window."

though this is not implemented the same way in all the different browsers we got these days.

document.getElementsByClassName('item_1')[0].scrollIntoView();

Or you could assign an id to the first item, or pass this id: 'ul-main_wrapper' and pass it to this example function

function scrollToAnchor(anchor) {
   var scrollLocation = document.location.toString().split('#')[0];
   document.location = scrollLocation + '#' + anchor;
}

which will do the scrolling for you.

If you do use jquery, use the solution by mmm

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