由于标头,scrollto offset javascript出现问题 [英] Problem with scrollto offset javascript because of header
问题描述
我需要有关此scrollto代码段的帮助.问题是我需要为菜单设置一个偏移量.没有偏移量,我滚动到的标题将隐藏在菜单下方.请自行查看: https://julyfx.mystagingwebsite. com/stanford-mba-msx-essay-topic-analysis-examples/ 有人碰巧有建议吗? 谢谢!利亚
I need help with this scrollto code snippet. The problem is that I need to set an offset to account for my menu. Without the offset the header that I scroll to gets buried underneath the menu. See for yourselves here:https://julyfx.mystagingwebsite.com/stanford-mba-msx-essay-topic-analysis-examples/ Would anyone happen to have a suggestion? Thank you! Leah
<script type="text/javascript">
jQuery(document).ready(function($) {
$('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
};
});
}
}
});
});
</script>
推荐答案
应该相对容易:例如,如果标头高85像素,则可以将这些85像素添加到代码的偏移量中,因此此行
Should be relatively easy: If your header is for example 85px high, you can just add these 85px to the offset in your code, so this line
scrollTop: target.offset().top
成为
scrollTop: target.offset().top - 85
这样,窗口将比计算的滚动少85px,因此该部分不会隐藏在标题后面.
that way the window will scroll 85px less than calculated, so the section will not be hidden behind the header.
这篇关于由于标头,scrollto offset javascript出现问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!