简体   繁体   English

jQuery在调整大小时添加类,窗口宽度不正确

[英]Jquery add class on resize, window width not correct

I had a question about something weird. 我有一个奇怪的问题。 I have been using jquery window.with and window.resize but I don't feel like it is accurate, I have set it to do something at max-width 1200px, but it does it at 1280px? 我一直在使用jquery window.with和window.resize,但是我不觉得它是准确的,我已经将它设置为以最大宽度1200px做某事,但是它以1280px做事? Is there something wrong with my code? 我的代码有问题吗?

jQuery(window).resize(function() {
        if (jQuery(window).width() <= 1200) {
            if(!jQuery(".navbar-collapse .nav li").hasClass("fa fa-chevron-down")) {
                document.querySelector('style').textContent += "@media screen and (max-width: 1200px) { " +
                    ".fa, .fa-chevron-down:hover { color: black; }" +
                    ".fa-chevron-down:before {content: normal;}" +
                    ".nav .parent:before {display: inline-block;\n" +
                    "        content: '\\f078';\n" +
                    "        -webkit-border-after-width: 20px;\n" +
                    "        top: 7px;\n" +
                    "        position: absolute;\n" +
                    "        right: 24px;\n" +
                    "        font-size: 25px;\n" +
                    "        z-index: 8;}" +
                    "" +
                    "}";
            }
            jQuery('.navbar-collapse .nav li').addClass("fa fa-chevron-down");
        }
        else if(jQuery(window).width() >= 1201) {
            jQuery('.navbar-collapse .nav li').removeClass("fa fa-chevron-down");
        }
    });

Does anyone know how to fix this problem so it just adds the class at 1200px and removes it as 1201px? 有谁知道如何解决此问题,所以它只将类添加为1200px并将其删除为1201px?

I believe the problem is, that the window.width() returns the width of the window including scrollbars etc. (pls, correct me if I'm wrong...). 我相信问题是,window.width()返回窗口的宽度,包括滚动条等。(请,如果我错了,请纠正我...)。 I have once needed something similar and I used a function to determine the width: 我曾经需要类似的东西,并且使用函数来确定宽度:

function viewport() {
  var e = window, a = 'inner';
  if (!('innerWidth' in window )) {
    a = 'client';
    e = document.documentElement || document.body;
  }
  return { width : e[ a+'Width' ] , height : e[ a+'Height' ] };
}

With this you can check for the window-width as follows: 这样,您可以检查窗口宽度,如下所示:

if ((viewport().width <= 1200)

remove jQuery(window).resize(function() 删除jQuery(window).resize(function()

fiddle link that works fair simple 小提琴的链接 ,很简单

if (jQuery(window).width() < 767) {
$("p").append("<b>Appended text less than 767</b>");
}
else if(jQuery(window).width() > 767) {
$("p").append("<b>Appended text greater than than 767</b>");
}

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

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