admin管理员组

文章数量:1313284

I want to reset a particular element once the browser window has been resized from any size less than 641px, to a greater size. Here is an example of what I am trying to achieve, written in pseudo code:

if (browser.window <= 641px && browser.window.resizedTo > 641px) {
  $( ".foo" ).removeClass( "bar" )
}

Thank you!

I want to reset a particular element once the browser window has been resized from any size less than 641px, to a greater size. Here is an example of what I am trying to achieve, written in pseudo code:

if (browser.window <= 641px && browser.window.resizedTo > 641px) {
  $( ".foo" ).removeClass( "bar" )
}

Thank you!

Share Improve this question asked Mar 3, 2016 at 19:12 Ralph David AbernathyRalph David Abernathy 5,51813 gold badges56 silver badges87 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 7

I'll assume for the sake of this question that you mean 641px as the width, but I left the innerHeight variable there, too, in case you need it:

// Closure last-height/width
var lastX = window.innerWidth
var lastY = window.innerHeight

function fooOnResize() {
   var x = window.innerWidth
   var y = window.innerHeight
   if (lastX <= 641 && 641 < x) {
      $(".foo").removeClass("bar")
   }
   lastX = x
   lastY = y
}

window.addEventListener("resize", fooOnResize)
// Also okay: window.onresize = fooOnResize

The trick is to basically hold the last size in some closure variables, then on resize, you can make your parison. After you have done the parison and the work, you store the current x/y as the last ones, for the next resize.

Try the window.onresize event:

https://developer.mozilla/en-US/docs/Web/API/GlobalEventHandlers/onresize

You can get the current dimensions of the browser window using window.innerHeight and window.innerWidth:

window.onresize = function() {
    console.log('height: ' + window.innerHeight);
    console.log('width: ' + window.innerWidth);
}

本文标签: javascriptDetect when browser window has been resized from certain size to a larger sizeStack Overflow