最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - onresize does not work - Stack Overflow

programmeradmin2浏览0评论

I'm doing a responsive site then a I'm using:

window.addEventListener("resize", function(){
   if(window.innerWidth < 768){
      //execute some code
   }
   else{
      //execute some code
   }
});

When my navigator is at full width and click at the "Restore Down" button the window is resized to a width less then 768 the code inside of addEventListener("resize") doesn't work. These images below shows the condition of this "resize". My code works only when I resize the window using the pointer of the mouse.

Any solution for this situation?

I'm doing a responsive site then a I'm using:

window.addEventListener("resize", function(){
   if(window.innerWidth < 768){
      //execute some code
   }
   else{
      //execute some code
   }
});

When my navigator is at full width and click at the "Restore Down" button the window is resized to a width less then 768 the code inside of addEventListener("resize") doesn't work. These images below shows the condition of this "resize". My code works only when I resize the window using the pointer of the mouse.

Any solution for this situation?

Share asked Dec 9, 2014 at 11:41 Alessander FrancaAlessander Franca 2,8012 gold badges31 silver badges53 bronze badges 6
  • It's working for me in Chrome: jsfiddle/lharby/xx6eb7gb – lharby Commented Dec 9, 2014 at 11:46
  • Thank you. The problem may be some framework that I'm using. – Alessander Franca Commented Dec 9, 2014 at 11:52
  • Hmmm, difficult to tell, if you can make a fiddle you can include other js files/frameworks if they are hosted somewhere (cdn etc). – lharby Commented Dec 9, 2014 at 11:55
  • Sorry, I can't =( I would like so much to do this but I can't show my code and it's hard to reproduce the problem because I'm using Drupal. – Alessander Franca Commented Dec 9, 2014 at 12:08
  • I wonder then if you are seeing another js error which is stopping the resize function running. – lharby Commented Dec 9, 2014 at 12:22
 |  Show 1 more ment

2 Answers 2

Reset to default 4

onresize doesn't fire with attachEvent or addEventListener. you must attach your callback directly to window.onresize.

syntax

window.onresize = funcRef;

example

window.onresize = resize;

function resize() {
    alert("resize event detected!");
}

Try the window.onresize event.

window.onresize = function ResizeApp()
{
  if(window.innerWidth < 768)
  {
    //execute some code
  }
  else
  {
    //execute some code
  }
}
发布评论

评论列表(0)

  1. 暂无评论