gpt4 book ai didi

javascript - 使用 jQuery 根据屏幕大小更改某些功能

转载 作者:行者123 更新时间:2023-11-30 05:38:37 26 4
gpt4 key购买 nike

嘿,我正在尝试根据屏幕分辨率更改网页的功能。现在在某种程度上它工作正常,但问题是每次我更改分辨率时,整个功能都必须再次呈现。举例来说,如果我必须根据屏幕尺寸加载不同版本的图像并且我是中等尺寸,如果我调整大小并且我仍然处于中等分辨率则图像必须重新加载。现在我正在使用 $(window).resize(checkMedWidth); 但如果我是中等大小,则必须有一些方法来获得加载的 hld。我的代码是

$(document).ready(function() {

// Optimisation: store the references outside the event handler:
var $window = $(window);

var currentWindowSize;

var flagIs;
$(window).resize(function () {
currentWindowSize = $window.width();
if (currentWindowSize >= 0 && currentWindowSize <= 999) {
$('body').css('background-color', 'red');
flagIs = "low";

}
else if (currentWindowSize >= 1000 && currentWindowSize <= 1336) {

$('body').css('background-color', 'green');
flagIs = "high";
}

});

最佳答案

$(document).ready(function() {

// Optimisation: store the references outside the event handler:
var $window = $(window),
currentWindowSize,
flagIs,
flagWas = '';

function res() {
currentWindowSize = $window.width();

//set flag string to LOW if...
if (currentWindowSize <= 999) {
flagIs = "low";
}
//set flag string to HIGH if...
else if (currentWindowSize >= 1000 && currentWindowSize <= 1336) {
flagIs = "high";
}
// on first call function compare zero string flagWas and current string (for example) 'low'
//on other calls function will compare current string and the past string
// if they are different (it happens if user change browser window width AND new window width walk into different width interval) or ( on the first iteration past string = '' and new string =/= '' (just containsa some string, for example 'low' ))
if (flagIs != flagWas)
{
// if new string is low - so change css to low setting
if (flagIs == 'low') {
$('body').css('background-color', 'red');
}
// if new string is high - so change css to high setting
else if (flagIs == 'high') {
$('body').css('background-color', 'green');
}
//after we done with all this just write our present flagString to pastString (so we can use it later for compare like we did it before, variables are global, so we can access them from one iteration to another)
flagWas = flagIs;
}
}

// Execute function on load
res();

// the same function will be execute each time we resize window
$(window).resize(function () {
res();
});
});

这里是JSFiddle link
老实说,我第一个答案中的代码更好,它也能解决你的任务。 :)

关于javascript - 使用 jQuery 根据屏幕大小更改某些功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22111795/

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