JS - windows的宽度从大于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

本文关键字:800px 一个 windows 大于 JS 像素      更新时间:2023-09-26

这是一个非常直接的问题。

我有一个想要的操作,当我改变窗口大小,屏幕宽度低于800px时调用。

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

我实际上想做的是有所需的动作触发当窗口的宽度从高于800像素的数量减少到低于800。

例如,它现在的功能是,当窗口大小调整到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
});