2017-10-04 94 views
0
$(document).ready(function(){ 
    // Add smooth scrolling 
    $('.button').children().onclick(function(event) { 

    // Make sure this.hash has a value before overriding default behavior 
    if (this.hash !== "") { 
     // Prevent default anchor click behavior 
     event.preventDefault(); 

     // Store hash 
     var hash = this.hash; 

     // Using jQuery's animate() method to add smooth page scroll 

     $('html, body').animate({ 
     scrollTop: $(hash).offset().top 
     }, 1000, function(){ 
     // Add hash (#) to URL when done scrolling (default click behavior) 
     window.location.hash = hash; 

     }); 
    } // End if 
    }); 
}); 




$(document).ready(function(){ 
    // Add smooth scrolling to all links 
    $('.button').children().on('click', function(event) { 

    // Make sure this.hash has a value before overriding default behavior 
    if (this.hash !== "") { 
     // Prevent default anchor click behavior 
     event.preventDefault(); 

     // Store hash 
     var hash = this.hash; 

     // Using jQuery's animate() method to add smooth page scroll 
     // The optional number (800) specifies the number of milliseconds it takes to scroll to the specified area 
     $('html, body').animate({ 
     scrollTop: $(hash).offset().top 
     }, 1000, function(){ 

     // Add hash (#) to URL when done scrolling (default click behavior) 
     window.location.hash = hash; 
     }); 
    } // End if 
    }); 
}); 

当我使用onclick()函数时,单击按钮时没有滚动效果;它只跳转到没有任何滚动效果的文章。onclick()和.on('click',function())之间的区别?

但是,当我使用('点击',功能())有一个滚动效果。

这两者有什么区别?

+0

回答了几次......这里:https://stackoverflow.com/questions/6348494/addeventlistener-vs-onclick – magreenberg

+0

这个问题是不一样的。这是比较'addEventListener()'到'onclick()'。这个问题特别针对jQuery的方法。 –

回答

1
  • .onclick()是Javascript函数
  • .click().on("click")是jQuery函数,和jQuery增加了一些更多的功能其功能。
相关问题