简体   繁体   English

JavaScript对象文字和jQuery $(类)

[英]JavaScript Object Literal and jQuery $(classes)

I have an object that contains a list of browser widths 我有一个包含浏览器宽度列表的对象

breakpoints {
    smallMobile: 0, 
    mobile: 480, 
    tablet: 672, 
    desktop: 868, 
    largeDesktop: 1050
}

I want to add a class to the body of the document based on whether the browser width falls between two values in the breakpoints object. 我想根据浏览器的宽度是否介于断点对象的两个值之间,将一个类添加到文档的body中。

What I have so far 到目前为止我有什么

var key;

for (key in breakpoints) {
    if (breakpoints.hasOwnProperty(key))
        if (winWidth >= breakpoints[key]) {
            $('body').removeClass().addClass(key);
        } else {
            $('body').removeClass(key);
        }
    }
}

Now this works, however it also removes ALL classes from the body . 现在可以使用,但是它也会从body删除所有类。 Instead I would like to add only one class, and not have to remove anything unless the breakpoint no longer matches. 相反,我只想添加一个类,而不必删除任何东西,除非断点不再匹配。

I'm sure there has to be a way. 我敢肯定一定有办法。 Any help would be appreciated :) 任何帮助,将不胜感激 :)

EDIT 编辑

Current output at various widths 各种宽度的电流输出

>= 1050: <body class="smallMobile mobile tablet desktop largeDesktop"> > = 1050: <body class="smallMobile mobile tablet desktop largeDesktop">

>= 868: <body class="smallMobile mobile tablet desktop"> > = 868: <body class="smallMobile mobile tablet desktop">

>= 672: <body class="smallMobile mobile tablet"> > = 672: <body class="smallMobile mobile tablet">

Ideal output 理想输出

>= 1050: <body class="largeDesktop"> > = 1050: <body class="largeDesktop">

>= 868: <body class="desktop"> > = 868: <body class="desktop">

>= 672: <body class="tablet"> > = 672: <body class="tablet">

(For the record I use Media Queries, but I need access to classnames for an edge case) (出于记录目的,我使用媒体查询,但是我需要访问边缘情况的类名)

I've slightly modified your code and saved the class thats the highest applicable one. 我已经稍微修改了您的代码,并保存了最适用的类。 Then I remove every class and apply the applicable one. 然后,我删除每个类别并应用适用的类别。

// create a variable to store the only class you want to apply
var apply = "";
for (var key in breakpoints) {
    // keep overwriting the apply var if the new key is applicable
    if (winWidth >= breakpoints[key]) {
       apply = key;
    }
    // remove any existing classes with that keyname
    $('body').removeClass(key);
}
// add the key to the body as a class
$('body').addClass(apply);

Also, you can remove breakpoints.hasOwnProperty(key) as the for -loop only loops through keys that actually exist anyway, so you are doing an unnecessary check. 另外,您可以删除breakpoints.hasOwnProperty(key)因为for -loop仅循环通过实际上仍然存在的键,因此您进行了不必要的检查。

Update 更新资料

At @juvian's note, I'll add a way to make sure that the order in which you make your object makes no difference: 在@juvian的注意下,我将添加一种方法来确保您制作对象的顺序没有区别:

var apply = "";
var check = 0;
for (var key in breakpoints) {
    // Also check if the value is higher than the last set value
    if (winWidth >= breakpoints[key] && breakpoints[key] >= check) {
        apply = key;
        check = breakpoints[key];
    }
    $('body').removeClass(key);
}
$('body').addClass(apply);

It's because you're using removeClass() without any parameter in it. 这是因为您使用的是removeClass(),其中没有任何参数。

If a class name is included as a parameter, then only that class will be removed from the set of matched elements. 如果将类名作为参数包括在内,则只有该类将从匹配的元素集中删除。 If no class names are specified in the parameter, all classes will be removed. 如果在参数中未指定类名,则将删除所有类。

Source: http://api.jquery.com/removeClass/ 资料来源: http//api.jquery.com/removeClass/

So, you should find the right class to remove and then call this function with a param. 因此,您应该找到要删除的正确类,然后使用参数调用此函数。

Consider to store your breakpoints in sorted array instead of map: 考虑将断点存储在排序数组而不是map中:

var dimensions = [];
for (var key in breakpoints) {
   dimensions.push({ name: key, width: breakpoints[key] })
}

dimensions.sort(function(a, b) { return b.width - a.width });

Now dimensions is 现在尺寸是

[
    {"name":"largeDesktop","width":1050},
    {"name":"desktop","width":868},
    {"name":"tablet","width":672},
    {"name":"mobile","width":480},
    {"name":"smallMobile","width":0}
]

Of course you can hardcode it in this structure and not grep/sort each time. 当然,您可以按此结构对其进行硬编码,而不必每次都进行grep / sort。

Finally, find highest width with 最后,用

for (var i = 0; i < dimensions.length; i++) {
    if (winWidth >= dimensions[i].width) {
        $("body").addClass(dimensions[i].name);
        break;
    }
} 

However, if you want to create responsive layout, media queries is the way to go. 但是,如果要创建响应式布局,则可以使用媒体查询。 Media queries also will take windows resize/orientation change events into account. 媒体查询还将考虑Windows调整大小/方向更改事件。

Here is a way you can get the one that matches with the highest value: 您可以通过以下方式获得与最大值匹配的商品:

var wid = 868;
var max = 0;
var size = null;

Object.keys(breakpoints).map(function(a){
    size = wid >= breakpoints[a] ? a : size;
    max = wid >= breakpoints[a] ? Math.max(max,breakpoints[a]) : max;
})
console.log(max, size) // 868, 'desktop'

if you use .removeClass() without parameter then all class on selected element will remove as like prabu said, but if you want, i give some example so you will not confused how to remove class if window width less than breakpoints 如果您使用不带参数的.removeClass(),则所选元素上的所有类都会像prabu所说的那样被删除,但是如果您愿意,我举一些例子,这样您就不会混淆如果窗口宽度小于断点时如何删除类

var key;
for (key in breakpoints) { 
    if (breakpoints.hasOwnProperty(key)) {
        $("body").addClass(key);
        if (winWidth<breakpoints[key]) {
            $("body").removeClass(key);
        }
    }
} 

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

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