How can I tell if a page has jumped to the anchor (#) in javascript?

前端 未结 3 1223
抹茶落季
抹茶落季 2021-02-08 11:29

I have some javascript that can appear on many different pages. Sometimes those pages have been accessed via a URL containing an anchor reference (#comment-100, for instance).

相关标签:
3条回答
  • 2021-02-08 11:31

    Seems like you could use window.onscroll. I tested this code just now:

    <a name="end" />
    <script type="text/javascript">
        window.onscroll = function (e) {
            alert("scrolled");
    }
    </script>
    

    which seems to work.

    Edit: Hm, it doesn't work in IE8. It works in both Firefox and Chrome though.

    Edit: jQuery has a .scroll() handler, but it fires before scrolling on IE and doesn't seem to work for Chrome or Firefox.

    0 讨论(0)
  • 2021-02-08 11:44

    You can check window.onhashchange in modern browsers. If you want cross compatible, check out http://benalman.com/projects/jquery-hashchange-plugin/

    This page has more info on window.onhashchange as well.

    EDIT: You basically replace all anchor names with a similar linking convention, and then use .scrollTo to handle the scrolling:

    $(document).ready(function () {
      // replace # with #_ in all links containing #
      $('a[href*=#]').each(function () {
          $(this).attr('href', $(this).attr('href').replace('#', '#_'));
      });
    
      // scrollTo if #_ found
      hashname = window.location.hash.replace('#_', '');
      // find element to scroll to (<a name=""> or anything with particular id)
      elem = $('a[name="' + hashname + '"],#' + hashname);
    
      if(elem) {
           $(document).scrollTo(elem, 800,{onAfter:function(){
            //put after scroll code here }});
      }
    });
    

    See jQuery: Scroll to anchor when calling URL, replace browsers behaviour for more info.

    0 讨论(0)
  • 2021-02-08 11:53

    To detect when the element appears on the screen, use the appear plugin:

    $('#comment-1').appear(function() {
      $(this).text('scrolled');
    });
    
    0 讨论(0)
提交回复
热议问题