如果屏幕有一定宽度,请运行代码

wil*_*rot 4 javascript if-statement screen width

当窗口大小小于700像素时,我只是想在控制台中写一条消息.

我尝试的是:

if(window.innerWidth < 700){
console.log("hello");
}
Run Code Online (Sandbox Code Playgroud)

if(screen.width < 700){
console.log("hello");
}
Run Code Online (Sandbox Code Playgroud)

我没有得到任何错误meassages但代码不运行.如果我在700之后发布"px"我得到错误meassage"Uncaught SyntaxError:Unexpected identifier".

Pra*_*man 7

你需要把这个里面windowresize事件监听器.而且你需要使用window.innerWidth它,它总是返回一个整数值.

if (window.attachEvent) {
  window.attachEvent('onresize', function() {
    if (window.innerWidth < 760)
      console.log("Less than 760");
    else
      console.log("More than 760");
  });
} else if (window.addEventListener) {
  window.addEventListener('resize', function() {
    if (window.innerWidth < 760)
      console.log("Less than 760");
    else
      console.log("More than 760");
  }, true);
} else {
  //The browser does not support Javascript event binding
}
Run Code Online (Sandbox Code Playgroud)