【发布时间】:2018-03-15 12:33:10
【问题描述】:
$(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() 函数时,单击按钮时没有滚动效果;它只跳转到文章,没有任何滚动效果。
但是当我使用 on('click',function()) 有滚动效果。
这两者有什么区别?
【问题讨论】:
-
那个问题不一样。这是将
addEventListener()与onclick()进行比较。这个问题专门针对 jQuery 的方法。
标签: javascript jquery html css