gpt4 book ai didi

jquery - 如果浏览器宽度发生变化则运行脚本

转载 作者:行者123 更新时间:2023-12-01 04:44:31 27 4
gpt4 key购买 nike

我有一个 1 页网站,当单击导航按钮时,它会滚动到选定的 div。

在宽度为1006px或以上的浏览器上,标题将显示高度:60px;固定在顶部。

我有以下脚本,它在宽度超过 1006px 的浏览器上运行得很好,但在移动版本上,我在顶部有 60px 的间隙。

这是我需要编辑的行

var offsetHeader = 60;

var divPos = $(theID).offset().top-60;

正如你所注意到的,我设置了 60,这是 div 的高度,我可以将其更改为 0,这样就可以在移动版本上完美工作,我需要对其进行编辑,以便当浏览器的宽度发生变化时这将更改为 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;
}
}

最佳答案

我并没有真正理解目标,但这也许会有所帮助:

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;
}
}

关于jquery - 如果浏览器宽度发生变化则运行脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31992378/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com