2017-06-24 42 views
-1

任何人都可以向我解釋下面的代碼。我的意思不是語法,而是邏輯。我想實現滾動到單擊事件的div,但我不完全明白這將如何完成。如何滾動到div工作?

$('a[href*="#"]') 
 
    // Remove links that don't actually link to anything 
 
     .not('[href="#"]') 
 
     .not('[href="#0"]') 
 
     .click(function(event) { 
 
     // On-page links 
 
     if (
 
      location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') 
 
      && 
 
      location.hostname == this.hostname 
 
     ) { 
 
      // Figure out element to scroll to 
 
      var target = $(this.hash); 
 
      target = target.length ? target : $('[name=' + this.hash.slice(1) + ']'); 
 
      // Does a scroll target exist? 
 
      if (target.length) { 
 
      // Only prevent default if animation is actually gonna happen 
 
      event.preventDefault(); 
 
      $('html, body').animate({ 
 
       scrollTop: target.offset().top 
 
      }, 1000, function() { 
 
       // Callback after animation 
 
       // Must change focus! 
 
       var $target = $(target); 
 
       $target.focus(); 
 
       if ($target.is(":focus")) { // Checking if the target was focused 
 
       return false; 
 
       } else { 
 
       $target.attr('tabindex','-1'); // Adding tabindex for elements not focusable 
 
       $target.focus(); // Set focus again 
 
       }; 
 
      }); 
 
      } 
 
     } 
 
     });

+0

您能更具體地說明您想向您解釋的內容嗎? – Icepickle

回答

-1

所以,下手 - 這是一個非常糟糕的代碼示例 - 沒有階級,沒有選擇並且代碼相當晦澀;)

的滾動什麼是重要的,雖然,這條線:

$('html, body').animate({ 
    scrollTop: target.offset().top 
}, 1000, function() (...) 

這裏發生的事情 - 主要htmlbody實體觸發動畫 - 將滾動區域的頂部移動到作爲事件目標的target的頂部邊緣。 offset()是返回目標座標的函數。

至於整個代碼 - 它基本上檢查URL是否有一個特殊的散列,指向應該成爲滾動窗口頂部的元素並搜索DOM中的元素($(this.hash)),獲取其座標併爲滾動本身運行JQuery動畫。

+0

當然,整個代碼可以替換爲「完全沒有」,它將提供完全相同的功能...... –

+0

'$(this.hash)'與*「座標」無關* – charlietfl

+0

'$(this .hash)成爲用於獲得'offset()'然後用於滾動到的目標...因此,在$(this.hash)中找到的元素然後成爲main在滾動區域。 – SzybkiSasza