2017-08-28 134 views
0

我有点新来的代码,但当我尝试使用jQuery脚本平滑滚动它从来没有工作。jQuery的平滑滚动不能在我的网站上工作

如果我点击我的按钮它滚动到div,但不顺利。

// Document ready shorthand statement 
 
$(function() { 
 
    $('.link').click(function() { 
 
     var id = $(this).attr('href'); 
 
     $('html,body').animate({ 
 
      scrollTop: $(id).offset().top 
 
     }, 'slow'); 
 
     // Prevent default behavior of link 
 
     return false; 
 
    }); 
 
});
#portfolio {/* just to make it visible */ 
 
    margin-top: 100vh; 
 
}
<a href="#portfolio"><button type="button" class="btn btn-lg btn-outline-info">Scroll down</button></a> 
 

 
<div id="portfolio" class="container pt-5"> 
 
    <div class="row d-flex justify-content-center"> 
 
     <img id="thumb" src="images/img/01.jpg" class="img-thumbnail m-2 img-responsive" width="300" height="200"> 
 
    </div> 
 
</div> 
 

 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

+0

只是一个小的事情 - 看我的答案......问候:) – Axel

回答

1

你刚才忘添加类 “链接” 在您的标记......

$(function() { 
 
    // Hint: in this implementation you even don't need to specify a class and write 
 
    // "$('a').click(function(oEvent) {" instead 
 
    $('.link').click(function(oEvent) { 
 
     var id = $(this).attr('href'), 
 
      $target = $(id); 
 
     if ($target.length) { // check if there is a valid target first @Hint 
 
      oEvent.preventDefault(); // Prevent default behavior of link 
 
      $('html,body').animate({ 
 
       scrollTop: $target.offset().top 
 
      }, 'slow'); 
 
      // return false prevents event from bubbling which isn't a good practice 
 
     } 
 
    }); 
 
});
#portfolio {/* just to make it visible */ 
 
    margin-top: 100vh; 
 
}
<!-- dont't forget to add your class "link" --> 
 
<a href="#portfolio" class="link"><button type="button" class="btn btn-lg btn-outline-info">Scroll down</button></a> 
 

 
<div id="portfolio" class="container pt-5"> 
 
    <div class="row d-flex justify-content-center"> 
 
    <img id="thumb" src="images/img/01.jpg" class="img-thumbnail m-2 img-responsive" width="300" height="200"> 
 
    </div> 
 
</div> 
 

 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

编辑|先进的片断(附加散列网址平滑滚动结束后)

$(function() { 
    $('body').click(function(oEvent) { 
     var $link = $(oEvent.target),$target, sUrl; 
     if ($link[0].hash || ($link = $link.closest('a'))[0].hash) { 
      $target = $($link[0].hash); 
      if ($target.length) { 
       oEvent.preventDefault(); 
       sUrl = window.location + $link[0].hash 
       $('html,body').animate(
        { scrollTop: $target.offset().top }, 
        'slow', 
        function() { window.location = sUrl; } // set new location 
       ); 
      } 
     } 
    }); 
}); 

如果你想/需要一些更深层次的explanantions让我知道...

+0

它仍然没有工作...可以因为我使用bootstrap 4? – Goestav

+0

更新:我找到了。我忘了包含jQuery脚本 – Goestav

+0

如果您需要对平滑滚动进行更深入的解释,请告诉我。问候 :) – Axel