在函数中包装代码。 noob这里 [英] wrap code in a function. noob here
本文介绍了在函数中包装代码。 noob这里的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
if($(window).width()> 980)我试图包装这段代码: {
$(window).on(scroll,function(){
if($(window).scrollTop()> 20){
//添加黑色背景
$(。x-navbar)。addClass(active);
$(。x-navbar .desktop .x-nav li a)。addClass(small-bar);
}
else {
//删除背景
$(。x-navbar)。removeClass(active);
$(。x- navbar .desktop .x-nav li a)。removeClass(small-bar);
}
});
}
在一个函数中,这样我可以在980px宽度下禁用它。 p>
我试图存档的东西是这样的:
创建一个函数,如下所示: p>
navBar = function(){
//整个代码都在这里。
}
然后在980像素宽度下在手机中禁用它:
if($(window).width()<980){
//不要运行函数称为navBar。
$ / code>
我遇到的问题是,如果窗口被调整为宽度在980px以上的代码不会听调整大小,它会运行。
解决方案
正如我在评论中提到
$(window).on(scroll resize,function(){
if($(window).width( )> 980){
if($(window).scrollTop()> 20){
//添加黑色背景
$(。x-navbar)。addClass( active);
$(。x-navbar .desktop .x-nav li a).addClass(small-bar);
}
else {
//删除背景
$(。x-navbar)。removeClass(active);
$(。x-navbar .desktop .x-nav li a)。removeClass small-bar);
}
} else {
// if window width< 980
// remove background
$(。x-navbar ).removeClass(active);
$(。x-navbar .desktop .x-nav li a)。removeClass(sm全条);
}
});
I'm trying to wrap this code:
if($(window).width() > 980) {
$(window).on("scroll", function() {
if($(window).scrollTop() > 20) {
//add black background
$(".x-navbar").addClass("active");
$(".x-navbar .desktop .x-nav li a").addClass("small-bar");
}
else {
//remove background
$(".x-navbar").removeClass("active");
$(".x-navbar .desktop .x-nav li a").removeClass("small-bar");
}
});
}
in a function, so that I can disable it under 980px width.
The thing I'm trying to achive is something like this:
create a function as here under:
navBar = function () {
// the whole code goes here.
}
and then "disable" it in the mobile under 980px width like this:
if($(window).width() < 980) {
// DON'T run the funcion called "navBar".
}
The problem I'm having is that if the window gets resized to a width under 980px the code above will not listen to the resize and it will run anyway.
解决方案
as I mentioned in comment
$(window).on("scroll resize", function() {
if($(window).width() > 980) {
if($(window).scrollTop() > 20) {
//add black background
$(".x-navbar").addClass("active");
$(".x-navbar .desktop .x-nav li a").addClass("small-bar");
}
else {
//remove background
$(".x-navbar").removeClass("active");
$(".x-navbar .desktop .x-nav li a").removeClass("small-bar");
}
}else{
// if window width < 980
//remove background
$(".x-navbar").removeClass("active");
$(".x-navbar .desktop .x-nav li a").removeClass("small-bar");
}
});
这篇关于在函数中包装代码。 noob这里的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文