简体   繁体   English

编写以下jquery的更好方法

[英]Better way to write the following jquery

Im quite new to javaScript/jquery. 我对javaScript / jquery很陌生。 I wrote the following code to toggle a mobile Navigation but i am quite sure there is a simple way to combine the to following code blocks. 我编写了以下代码来切换移动导航,但是我很确定有一种简单的方法可以将以下代码块组合在一起。 i would appreciate advice how to write this a better, sleeker way. 我希望您能提出建议,以更好地,更时尚的方式编写此内容。 Thanks 谢谢

$(document).ready(function(){
var width = $(window).width();
    if(width <=500){
        $("nav").addClass("mobile").removeClass("desktop");
    }
    else{
        $("nav").removeClass("mobile").addClass("desktop");
    }

});

$(document).ready(function(){
  $(window).resize(function(){
    var width = $(window).width();
    if(width <=500){
        $("nav").addClass("mobile").removeClass("desktop");
    }
    else{
        $("nav").removeClass("mobile").addClass("desktop");
    }
});});

Simply create a single function and call it twice: 只需创建一个函数并调用两次:

function changeClasses() {
    var width = $(window).width();
    if(width <=500){
        $("nav").addClass("mobile").removeClass("desktop");
    }
    else{
        $("nav").removeClass("mobile").addClass("desktop");
    }
}

$(document).ready(changeClasses);
$(window).resize(changeClasses);

maybe better use css media queries... 也许更好地使用CSS媒体查询...

 @media screen and (max-width: 500px){ .desktop { width: or another rules... } } 

You can make it into a separate function which will clean it up a bit: 您可以将其设置为一个单独的函数,以对其进行清理:

function toggleClass() {
    var width = $(window).width();
    if(width <=500) {
        $("nav").addClass("mobile").removeClass("desktop");
    } else {
        $("nav").removeClass("mobile").addClass("desktop");
    }
}

$(document).ready(function(){
    toggleClass();
});

$(window).resize(function(){
    toggleClass();
});

You can always add the event once on resize then trigger the resize event. 您始终可以在调整大小后添加一次事件,然后触发调整大小事件。 I added a namespace to the event so that it will not conflict with any other window resize events when we trigger it. 我向事件添加了名称空间,以便在触发它时不会与任何其他窗口调整大小事件发生冲突。

$(window).on('resize.load', function() {
  var isMobile = $(window).width() < 500;
  $("nav").toggleClass("mobile", isMobile).toggleClass("desktop", !isMobile);
}).trigger('resize.load');

https://jsfiddle.net/r6myh0z8/ https://jsfiddle.net/r6myh0z8/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM