jQuery Smooth Scrolling on Page Load

后端 未结 5 1862
甜味超标
甜味超标 2021-01-02 16:24

I\'m using this jQuery Script to do Smooth Scrolling (Found on CSS-Tricks.com):

/** Smooth Scrolling Functionality **/
jQuery(document).ready(function($) {
          


        
5条回答
  •  孤独总比滥情好
    2021-01-02 17:12

    @ Talons post ...

    I found this to be the best way to do what I want so far:

    Me 2, but I had to make some changes to it.

    var target = jQuery(this).attr("href").replace('/', '');
    

    1. Why replace the "/"?

    In my case it makes the url...

    "http:// [my domain]/ [my page]/ [my anchor]" ...look like...

    "http:/ [my domain]/ [my page]/ [my anchor]"

    and...

    2. Chrome (my current version: 40.0.2214.115 m) doesn't like the following Line...

       jQuery('html,body').animate(
       {
           scrollTop: (jQuery(target).offset().top) - 100
       },500,function()
       {
           //location.hash = target;
       });
    

    Uncaught Error: Syntax error, unrecognized expression: http:/ [my domain]/ [my page]/ [my anchor]

    I found out that jQuery cannot work with "offset" when "target" is a full href like http:// .../#anchor.

    to fix 1.

    replaced:

    var target = jQuery(this).attr("href").replace('/', '');
    

    with:

    var target = jQuery(this).attr("href");
    

    to fix 2.

    replaced:

       jQuery('html,body').animate(
       {
           scrollTop: (jQuery(target).offset().top) - 100
       },500,function()
       {
           //location.hash = target;
       });
    

    with:

    if(target.search('/') === -1) { //only do scroll if page with anchor is the currently loaded page
       jQuery('html,body').animate(
       {
           scrollTop: (jQuery(target).offset().top) - 100
       },500"easeInOutExpo"); // requires easing
    }
    

    Now works perfectly for me, without any errors. Please comment on this one, for I am pretty new in js/jquery...

    thx @Talon

提交回复
热议问题