gpt4 book ai didi

javascript - 如何知道屏幕是缩小还是增加? [即时的]

转载 作者:行者123 更新时间:2023-11-30 15:44:00 25 4
gpt4 key购买 nike

我正在尝试检查用户是否减少增加屏幕。

我有以下功能并且工作正常,但它只依赖于初始屏幕尺寸:

var width = $(window).width();

$(function(){

$(window).resize(function(){

var resizeWidth = $(this).width();

if (resizeWidth > width) {

console.log('increased!')
width = width + 1;

} else {

console.log('reduced!')
width = width - 1;

}
});
});

是否可以随时知道屏幕是增大还是减小,而不是初始屏幕尺寸?

谢谢大家!

最佳答案

您设置的 window.resize 将连续触发。每次调整大小时只需存储旧宽度并将其与新宽度进行比较,比较后用新宽度替换旧宽度。

var win = $(window); // cache the window query since we'll be using it a lot

// set initial values
var oldWindowWidth = win.width();

// each time we resize
win.on('resize', function() {
// get the new width
var newWindowWidth = win.width();

// compare it to the old width
if (newWindowWidth > oldWindowWidth) {
console.log('increased');
}
else if (newWindowWidth < oldWindowWidth) {
console.log('descreased');
}

// update the old width
var oldWindowWidth = newWindowWidth;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

关于javascript - 如何知道屏幕是缩小还是增加? [即时的],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40369816/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com