简体   繁体   English

JS-窗口的宽度从高于800px的像素数量减少到800px以下导致触发动作

[英]JS - Window's width being decreased below 800px from an amount of pixels that are higher than 800px causes an action to trigger

A pretty straight forward question here. 这里是一个非常简单的问题。

I have a desired action that is called when I change the window size and the screen is below 800px in width. 我有一个所需的操作,当我更改窗口大小并且屏幕宽度小于800px时,将调用该操作。

$(window).resize(function() {
  if ($(window).width() < 800) {
    // this is where the magic happens
  }
});

What I actually want to do is have the desired action to trigger when the window's width is decreased to below 800 from an amount of pixels that is higher than 800. 我真正想做的是 ,当窗口的宽度从高于800的像素数量减少到800以下时,触发所需的操作。

For instance, how it functions now is that the desired action will be called any time the window is resized below 800. So adjusting it from 600px -> 800px will cause this action to be triggered again which is not what I want 例如,它现在的功能是在窗口调整到800以下时将调用所需的动作。因此,将其从600px-> 800px调整会再次触发此动作,这不是我想要的

var previousWidth; //Define global variable

$(window).ready(function() {
    previousWidth = $(window).width(); //Assign initial width when window is ready
};

$(window).resize(function() {
  var newWidth = $(window).width();
  if (previousWidth >= 800 && newWidth < 800 || //Will trigger when going from larger than 800px to smaller than 800px
      previousWidth < 800 && newWidth >= 800) { //Will trigger when going from smaller than 800px to larger than 800px
    // this is where the magic happens
  }
  previousWidth = newWidth; //Update previous width variable
});

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

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