我有以下代码,可以在大于768px(包含)的视口上为页面锚点产生良好的滚动效果。它将锚点的目标很好地置于#navbarTop
的高度之下。但是,在小视口上,它是一个不同的元素#menuMobile
,应该尊重它的高度。 #menu Mobile
是点击humburger菜单按钮时展开的链接列表。
$(document).ready(function() {
var headerHeight, part, place;
function getOffsets() {
headerHeight = $('#navbarTop').height();
}
$(window).load(getOffsets).resize(getOffsets);
$(function () {
$('.headerAnchor').click(function () {
part = $(this).attr('href');
place = $(part).offset().top - headerHeight;
$('html, body').animate({
scrollTop: place
}, 'slow');
return false;
});
});
});
主菜单的html:
<div class="navbar navbar-default navbar-fixed-top" id="navbarTop">
<div class="navbar-header">
<a href="#" class="navbar-brand" id="brand">Curriculum Vitae</a>
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
</div>
<ul id="menuMobile" class="nav navbar-nav navbar-right collapse navbar-collapse">
<li><a class="headerAnchor" href="#data">Dane <span>kontaktowe</span></a></li>
<li><a class="headerAnchor" href="#aspirations">Aspiracje <span>zawodowe</span></a></li>
<li><a class="headerAnchor" href="#qualifications">Kwalifikacje</a></li>
<li><a class="headerAnchor" href="#portfolio">Portfolio</a></li>
<li><a class="headerAnchor" href="#experience">Historia <span>zatrudnienia<span></a></li>
<li><a class="headerAnchor" href="#education">Wykształcenie</a></li>
<li><a class="headerAnchor" href="#skills">Umiejętności</a></li>
</ul>
</div>
我尝试调整JS代码,以便能够在移动视图上获得良好的滚动效果 - 相对于单击菜单按钮后始终保持打开的#menuMobile
的高度。但是,我无法取得适当的效果:
$(document).ready(function() {
var headerHeight, part, place;
function getOffsets() {
headerHeight = $('#navbarTop').height();
menuMobileHeight = $('#menuMobile').height();
}
$(window).load(getOffsets).resize(getOffsets);
$(function () {
$('.headerAnchor').click(function () {
part = $(this).attr('href');
place = $(part).offset().top - headerHeight;
placeMobile = $(part).offset().top - menuMobileHeight;
$('html, body').animate({
scrollTop: place
}, 'slow');
if ($(window).width() < 768) {
$('html, body').animate({
scrollTop: placeMobile
}, 'slow');
}
return false;
});
});
});
谁能说出我做错了什么?
答案 0 :(得分:0)
我设法找到了一种解决方案,通过以这种方式编写代码来获得适当的尺寸以滚动不同尺寸:
$(document).ready(function() {
var headerHeight, part, place;
function getOffsets() {
headerHeight = $('#navbarTop').height();
menuMobileHeight = $('#menuMobile').height() + 50;
}
$(window).load(getOffsets).resize(getOffsets);
$(function () {
$('.headerAnchor').click(function () {
part = $(this).attr('href');
place = $(part).offset().top - headerHeight;
placeMobile = $(part).offset().top - menuMobileHeight;
if ($(window).width() >= 768) {
$('html, body').animate({
scrollTop: place
}, 'slow');
}
if ($(window).width() < 768) {
$('html, body').animate({
scrollTop: placeMobile
}, 'slow');
}
return false;
});
});
});