简体   繁体   English

使用jQuery .resize()处理DOM

[英]Manipulating the DOM using jQuery .resize()

I want to change the order of elements in the DOM based on different browser sizes. 我想根据不同的浏览器大小更改DOM中元素的顺序。

I've looked into using intention.js but feel that it might be overkill for what I need (it depends on underscore.js ). 我已经研究过使用intention.js但是觉得它可能对我需要的东西来说是过高的(取决于underscore.js )。

So, i'm considering using jQuery's .resize() , but want to know if you think something like the following would be acceptable, and in line with best practices... 因此,我正在考虑使用jQuery的.resize() ,但想知道您是否认为以下内容是否可以接受,并且符合最佳实践...

var layout = 'desktop';
$( window ).resize(function() {
    var ww = $( window ).width();
    if(ww<=767 && layout !== 'mobile'){
        layout = 'mobile';
        // Do something here
    }else if((ww>767 && ww<=1023) && layout !== 'tablet'){
        layout = 'tablet';
        // Do something here
    }else if(ww>1023 && layout !== 'desktop'){
        layout = 'desktop';
        // Do something here
    }
}).trigger('resize');

I'm storing the current layout in the layout variable so as to only trigger the functions when the window enters the next breakpoint. 我将当前布局存储在layout变量中,以便仅在窗口进入下一个断点时才触发函数。

Media queries are generally preferred. 媒体查询通常是首选。 However, if I am in a situation where I am in a single page application that has a lot of manipulation during runtime, I will use onresize() instead. 但是,如果我处于一个在运行时具有很多操作的单页应用程序中,我将改用onresize()。 Javascript gives you a bit more freedom to work with dynamically setting breakpoints (especially if you are moving elements around inside the DOM tree with stuff like append()). Javascript为您提供了更大的自由来动态设置断点(尤其是如果您要使用诸如append()之类的东西在DOM树内部移动元素时)。 The setup you have is pretty close to the one I use: 您拥有的设置与我使用的设置非常接近:

function setWidthBreakpoints(windowWidth) {
    if (windowWidth >= 1200) {
        newWinWidth = 'lg';
    } else if (windowWidth >= 992) {
        newWinWidth = 'md';
    } else if (windowWidth >= 768) {
        newWinWidth = 'sm';
    } else {
        newWinWidth = 'xs';
    }
}

window.onresize = function () {

    setWidthBreakpoints($(this).width());

    if (newWinWidth !== winWidth) {
        onSizeChange();
        winWidth = newWinWidth;
    }
};

function onSizeChange() {
// do some size changing events here.
}

The one thing that you have not included that is considered best practice is a debouncing function , such as the one below provided by Paul Irish, which prevents repeated firing of the resize event in a browser window: 您尚未包括的被认为是最佳实践的一件事是防弹跳功能 ,例如Paul Irish提供的以下功能 ,它可以防止在浏览器窗口中重复触发resize事件:

(function($,sr){

  // debouncing function from John Hann
  // http://unscriptable.com/index.php/2009/03/20/debouncing-javascript-methods/
  var debounce = function (func, threshold, execAsap) {
      var timeout;

      return function debounced () {
          var obj = this, args = arguments;
          function delayed () {
              if (!execAsap)
                  func.apply(obj, args);
              timeout = null;
          };

          if (timeout)
              clearTimeout(timeout);
          else if (execAsap)
              func.apply(obj, args);

          timeout = setTimeout(delayed, threshold || 100);
      };
  }
  // smartresize 
  jQuery.fn[sr] = function(fn){  return fn ? this.bind('resize', debounce(fn)) : this.trigger(sr); };

})(jQuery,'smartresize');


// usage:
$(window).smartresize(function(){
  // code that takes it easy...
});

So incorporate a debouncer into your resize function and you should be golden. 因此,在您的调整大小功能中加入一个去抖器,您应该会很聪明。

在实践中最好使用媒体查询

Try this , I'm in a hurry atm and will refactor later. 试试这个 ,我很忙,以后会重构。

SCSS: SCSS:

body, html, .wrapper { width: 100%; height: 100% }

.sidebar { width: 20%; height: 500px; float: left;      
  &.mobile { display: none } }  

.content { float: right; width: 80% }

.red { background-color: red }
.blue { background-color: blue }
.green { background-color: green }

@media all and (max-width: 700px) {
  .content { width: 100%; float: left }
  .sidebar { display: none 
    &.mobile { display: block; width: 100% }
  }
}

HAML HAML

.wrapper
  .sidebar.blue
  .content.red
  .content.green
  .sidebar.mobile.blue 

On 700 px page breaks, sidebar disappears and mobile sidebar appears. 在700像素的分页符上,侧边栏消失,并且出现了移动侧边栏。 This can be much more elegant but you get the picture. 这样可能会更优雅,但您会明白。

Only possible downside to this approach is duplication of sidebar. 这种方法唯一可能的缺点是重复侧边栏。

That's it, no JS. 就是这样,没有JS。

Ok, the reason for my original question was because I couldn't find a way to move a left sidebar (which appears first in the HTML) to appear after the content on mobiles. 好的,我提出原始问题的原因是因为我找不到移动左侧内容栏(在HTML的最前面出现)以使其出现在移动内容之后的方法。

Despite the comments, I still can't see how using media queries and position or display alone would reliably solve the problem (perhaps someone can give an example?). 尽管有评论,但我仍然看不到单独使用媒体查询和positiondisplay如何可靠地解决问题(也许有人可以举个例子吗?)。

But, it did lead me to investigate the flexbox model - display: flex , and so I have ended up using that, and specifically flex's order property to re-arrange the order of the sidebars and content area. 但是,这确实促使我研究了flexbox模型-display display: flex ,因此我最终使用了它,特别是flex的order属性来重新排列侧边栏和内容区域的顺序。

Good guide here - https://css-tricks.com/snippets/css/a-guide-to-flexbox/ 此处的好指南-https: //css-tricks.com/snippets/css/a-guide-to-flexbox/

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

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