根据屏幕大小对div进行排序

时间:2022-01-11 20:24:51

I asked this question a few days ago about sorting div based on there class names. I was thinking, is it possible to sort the divs when the screen width is lower than 1200? Above the 1200 he sort the div-elements back on the old position? (It should even work when the screen resizes on the desktop)

几天前我问过这个问题,根据类名来排序div。我在想,当屏幕宽度低于1200时,是否可以对div进行排序?在1200以上,他将div元素重新排列在旧位置上? (当屏幕在桌面上调整大小时,它甚至可以工作)

I tried to save the old order in an array before this function runs. I add a data-attribute to every single row with a number 1 - x. But it is a little overkill I think..

在此函数运行之前,我尝试将旧订单保存在数组中。我为每一行添加一个数据属性,数字为1 - x。但我认为这有点过分。

var windowWidth = $(window).width();

order = function(){
    var elem = $('.container').find('.row').sort(sortMe);

    function sortMe(a, b) {
        return a.className.split(' ').pop() < b.className.split(' ').pop();
    }

    $('.container').append(elem);
};

// now the rows are sorted when the screen is smaller then 975 or 1185 but it possible to get the old order back when the screen is bigger then 975 or 1185 (when the screen resizes)
if($('body').hasClass('front')){
    if(windowWidth < 975){
        order();
    }
}else{
    if(windowWidth < 1185){
        order();
    }
}

Because on a desktop (> 1185) the admin decides the sorting in the CMS but if the screen is smaller than (< 1185) I decide the sorting and that is based on the class.

因为在桌面上(> 1185),管理员决定CMS中的排序,但如果屏幕小于(<1185),我决定排序,这是基于类。

1 个解决方案

#1


1  

I solved this problem by adding a data-attr before the order functions runs. When the screensize is bigger than x I sorting the element back based on the value of the data-attr without using an array. If it is smaller I sorting them based on my class.

我通过在订单函数运行之前添加data-attr解决了这个问题。当屏幕尺寸大于x时,我会根据data-attr的值对元素进行排序,而不使用数组。如果它更小我根据我的班级对它们进行排序。

You have two sorting functions, one for the desktop and one for the mobile. Works well for me.

您有两个排序功能,一个用于桌面,另一个用于移动。对我来说效果很好。

#1


1  

I solved this problem by adding a data-attr before the order functions runs. When the screensize is bigger than x I sorting the element back based on the value of the data-attr without using an array. If it is smaller I sorting them based on my class.

我通过在订单函数运行之前添加data-attr解决了这个问题。当屏幕尺寸大于x时,我会根据data-attr的值对元素进行排序,而不使用数组。如果它更小我根据我的班级对它们进行排序。

You have two sorting functions, one for the desktop and one for the mobile. Works well for me.

您有两个排序功能,一个用于桌面,另一个用于移动。对我来说效果很好。