Có một số cách để cuộn trơn tru khi nhấp vào liên kết nhảy (liên kết liên kết đến các phần trong cùng một trang) và đoạn mã đơn giản dưới đây là từ trang web của Paulund.
Nhưng trước tiên, đánh dấu mẫu:
Praesent tincidunt felis ed, a euismod quam dapibus tempus. Phasellus accumsan tellus dui. Nam ullamcorper hendrerit nunc, id eleifend dui fermentum sed. Mauris pulvinar non leo ở iaculis. Nuncequat mi lectus, sit amet egestas felis cursus sed. Proin lacinia nisl eu sodales nhạt nhẽo. Maecenas ultrices urna sed lectus pulvinar laoreet ut trong ante. Vestibulum et maximus risus. Praesent eu sodales nunc, et accumsan lectus.
Bước 1
Tạo một tệp có tên say, global.js trong thư mục chủ đề con của bạn js
(tạo, nếu không có) có mã sau:
jQuery(function( $ ){
// Smooth scrolling when clicking on a hash link
$('a[href^="#"]').on('click',function (e) {
e.preventDefault();
var target = this.hash;
var $target = $(target);
$('html, body').stop().animate({
'scrollTop': $target.offset().top
}, 900, 'swing');
});
});
Nếu bạn có tiêu đề cố định và muốn đặt độ lệch cho vị trí cuộn, hãy trừ chiều cao của phần tử cố định của bạn như sau:
'scrollTop': $target.offset().top-120
trong đó 120 là chiều cao tính bằng px của tiêu đề cố định trong ví dụ này.
Để đặt độ lệch ở độ rộng khung nhìn lớn hơn chiều rộng cụ thể, hãy sử dụng mẫu global.js này thay thế:
jQuery(function( $ ){
// Smooth scrolling when clicking on a hash link
$('a[href^="#"]').on('click',function (e) {
e.preventDefault();
var target = this.hash;
var $target = $(target);
if ( $(window).width() > 1023 ) {
var $scrollTop = $target.offset().top-120;
} else {
var $scrollTop = $target.offset().top;
}
$('html, body').stop().animate({
'scrollTop': $scrollTop
}, 900, 'swing');
});
});
Bước 2
Thêm phần sau vào functions.php của chủ đề con :
// Enqueue site-wide scripts
add_action( 'wp_enqueue_scripts', 'sk_enqueue_scripts' );
function sk_enqueue_scripts() {
wp_enqueue_script( 'global', get_stylesheet_directory_uri() . '/js/global.js', array( 'jquery' ), '', true );
}
Đó là nó.