我有一个1页的网站,当点击导航按钮时,它会滚动到所选的div。
在宽度为1006px或更高的浏览器上,标题将显示高度:60px;它固定在顶部。
我有以下脚本,在浏览器宽度超过1006px时工作得很好但是在移动版本上,我在顶部有60px的差距。
这是我需要编辑的行
var offsetHeader = 60;
和
var divPos = $(theID).offset().top-60;
正如您所注意到的,我有60套这是div的高度,我可以将其更改为0,这将在移动版本上完美运行,我需要编辑它以便在浏览器时# 39; s宽度变化然后这将变为60或0。
这里是完整的jQuery
jQuery(document).ready(function($) {
var offsetHeader = 60; //Add the height of the header if needed, also change line 31
$('.scroll').click(function(){
var $target = $($(this).attr('href'));
$(this).parent().addClass('active');
$('body').stop().scrollTo( $target , 800, {'axis':'y', offset: -offsetHeader});
return false;
});
/**
* This part handles the highlighting functionality.
* We use the scroll functionality again, some array creation and
* manipulation, class adding and class removing, and conditional testing
*/
var aChildren = $("nav ul li").children(); // find the a children of the list items
var aArray = []; // create the empty aArray
for (var i=0; i < aChildren.length; i++) {
var aChild = aChildren[i];
var ahref = $(aChild).attr('href');
aArray.push(ahref);
} // this for loop fills the aArray with attribute href values
$(window).scroll(function(){
var windowPos = $(window).scrollTop(); // get the offset of the window from the top of page
var windowHeight = $(window).height(); // get the height of the window
var docHeight = $(document).height();
for (var i=0; i < aArray.length; i++) {
var theID = aArray[i];
var divPos = $(theID).offset().top-60; // match the number with the offsetHeader
var divHeight = $(theID).height(); // get the height of the div in question
if (windowPos >= divPos && windowPos < (divPos + divHeight)) {
$("a[href='" + theID + "']").addClass("active");
} else {
$("a[href='" + theID + "']").removeClass("active");
}
}
if(windowPos + windowHeight == docHeight) {
if (!$("nav li:last-child a").hasClass("nav-active")) {
var navActiveCurrent = $(".nav-active").attr("href");
$("a[href='" + navActiveCurrent + "']").removeClass("nav-active");
$("nav li:last-child a").addClass("nav-active");
}
}
});
});
我正在考虑类似下面的代码,但不确定如何使用脚本实现它?
function updateContainer() {
var $containerWidth = $(window).width();
if ($containerWidth > 1006) {
var divPos = $(theID).offset().top-60;
var offsetHeader = 60;
} else {
var divPos = $(theID).offset().top-0;
var offsetHeader = 0;
}
}
答案 0 :(得分:1)
我真的不明白目标,但也许这会有所帮助:
var cWidth;
$(window).resize(function() {
cWidth = $(window).width();
if (cWidth > 1006) {
var divPos = $(theID).offset().top-60;
var offsetHeader = 60;
} else {
var divPos = $(theID).offset().top-0;
var offsetHeader = 0;
}
}
答案 1 :(得分:0)
使用窗口的resize事件
$(window).resize(updateContainer).resize();
通过在声明处理程序后触发事件,它也将在页面加载时触发