Когда я применяю этот скрипт, он переходит к ссылке, но я хочу, чтобы он располагался на 120 пикселей выше содержимого, на которое он ссылается.
Вот код:
<script>
$(document).ready(function(){
// Add smooth scrolling to all links
$("a").on('click', function(event) {
// Make sure this.hash has a value before overriding default behavior
if (this.hash !== 0) {
// 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
}, 800, function(){
// Add hash (#) to URL when done scrolling (default click behavior)
window.location.hash = hash;
});
} // End if
});
});
</script>
РЕДАКТИРОВАТЬ # 02
Вот мои HTML, CSS и Java для тех, кому интересно:
Так почему бы не scrollTop: ($(hash).offset().top-120)+"px"
?
@mplungjan axpers, он не работает, когда я меняю и заменяю код, потому что он возвращается в ту же позицию при использовании моего исходного кода.
Просто вычтите из своего расчета количество пикселей.
$(document).ready(function(){
// Add smooth scrolling to all links
$("a").on('click', function(event) {
// Make sure this.hash has a value before overriding default behavior
if (this.hash !== 0) {
// 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 -120
}, 800, function(){
// Add hash (#) to URL when done scrolling (default click behavior)
window.location.hash = hash;
});
} // End if
});
});
Это тоже не работает. когда я нажимаю те, они возвращаются назад, вам нужно дважды щелкнуть, прежде чем это произойдет. (ваш код работает, но вам нужно дважды щелкнуть)
проблема в том, что window.location.hash = hash;
после animate
выполняет второе действие, аналогичное действию по умолчанию. Замените его на history.pushState(null, null, hash);
, чтобы переписать историю URL и добавить хеш
$('html, body').animate({
scrollTop: $(hash).offset().top - 120
}, 800, function() {
// Add hash (#) to URL when done scrolling (default click behavior)
//window.location.hash = hash;
history.pushState(null, null, hash);
});
Ты потрясающий приятель.
Добро пожаловать в SO. Пожалуйста, добавьте соответствующий HTML-код в фрагмент, который я вам сделал. Пожалуйста, выберите также jQuery в качестве фреймворка. Нажмите редактировать, прокрутите вниз и нажмите Редактировать над фрагментом.