簡體   English   中英

如何向div添加平滑滾動

[英]How to add smooth scrolling to a div

我知道已經有答案了,但是我搜索了卻沒有任何效果,我也不知道為什么。

所以我想要的是通過標簽平滑滾動到div

我想要的是像這樣

所以我拿了js代碼,但對我來說根本無法工作,滾動完全失去了他的作用。

這是我的代碼:w HTML

<div class="col-lg-3 col-md-3 col-sm-3" id="some">
        <a href="#info" id="normal">
            <img src="imgs/product/normal.png" class="img-responsive">
        </a>
</div>

<!-- OTHER CONTENT -->

<div id="info">     
                Go here
</div>

和JS:

$("#some a[href^='#']").on('click', function(e) {
  // prevent default anchor click behavior
  e.preventDefault();
  // animate
  $('html, body').animate({
    scrollTop: $(this.hash).offset().top
  }, 300, function() {
    // when done, add hash to url
    // (default click behaviour)
    window.location.hash = this.hash;
  });
});

我不知道您是否復制>粘貼代碼,但是在ID之前缺少引號:

<div class="col-lg-3 col-md-3 col-sm-3 id="some">

那可能是一個解決方案,為什么它不起作用,因為那時$('#some a')不存在。

那是在您建立鏈接之前。 順便說一句,看看您的控制台,是否有任何錯誤消息?

將您的代碼更改為:

$("#some a").on('click', function(e) {

   // prevent default anchor click behavior
   e.preventDefault();

   e.stopImmediatePropagation();
   e.stopPropagation();
   var id = $(this).attr("href");
   // animate
   $('html, body').animate({
       scrollTop: $(id).offset().top
     }, 300, function(){

       // when done, add hash to url
       // (default click behaviour)
       window.location.hash = this.hash;
     });

});

只需使用下面的代碼片段即可實現,如您在帖子中所述。

$(function() {
  $('a').bind('click',function(event){
     var $anchor = $(this);
     $('html, body').stop().animate({
        scrollTop: $($anchor.attr('href')).offset().top
     }, 1000);       
      event.preventDefault();
   });
});

檢查演示

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM