gpt4 book ai didi

javascript - 仅在移动设备上使用某些 javascript 代码?

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

我正在尝试编写一种只允许此特定 javascript 代码在小于 900 像素的屏幕尺寸上运行的方法。此代码用于在移动设备上设置一个简单的左右导航按钮。但是,当我尝试使用 matchMedia 时,它完全弄乱了我的代码,但没有抛出任何错误。您将如何处理这个问题?

   var flavorScroll = (function() {

let widthMatch = window.matchMedia("(min-width: 901px)");


if (widthMatch.matches) {
var flavorBox1 = document.body.querySelector('#flavor-box-1');
var flavorBox2 = document.body.querySelector('#flavor-box-2');
var flavorBox3 = document.body.querySelector('#flavor-box-3');
var flavorBox4 = document.body.querySelector('#flavor-box-4');

var buttonRight = document.body.querySelector('#flavorButtonRight');
var buttonLeft = document.body.querySelector('#flavorButtonLeft');

var step = 1;

leftButton.style.visibility = 'hidden';

function flavorDisplayer(currentStep){
if(currentStep === 1) {
flavorBox1.style.display = 'block';

flavorBox2.style.display = 'none';

leftButton.style.visibility = 'hidden';
} else if(currentStep === 2) {
flavorBox2.style.display = 'block';

flavorBox1.style.display = 'none';
flavorBox3.style.display = 'none';

leftButton.style.visibility = 'visible';
} else if(currentStep === 3) {
flavorBox3.style.display = 'block';

flavorBox2.style.display = 'none';
flavorBox4.style.display = 'none';

rightButton.style.visibility = 'visible';
} else if(currentStep === 4) {
flavorBox4.style.display = 'block';

flavorBox3.style.display = 'none';

rightButton.style.visibility = 'hidden';
}
}





buttonRight.addEventListener('click', function() {
step += 1;

flavorDisplayer(step);
});

buttonLeft.addEventListener('click', function() {
step -= 1;

flavorDisplayer(step);
});

} else {

}

})();

最佳答案

这是我使用的一个方便的工具...

var breakpoint = {
is(s) {
const size = s.trim()
const sizes = {
xsmall: "480px",
small: "576px",
medium: "780px",
large: "992px",
xlarge: "1200px",
}

if (sizes.hasOwnProperty(size)) {
// return mq(`only screen and (min-width: ${sizes[size]})`)
return window.matchMedia(`only screen and (min-width: ${sizes[size]})`).matches
}

throw new ReferenceError(`The size ${size} is not a valid breakpoint: ${JSON.stringify(sizes)}`)
},
}

然后您可以将您的函数包装在一个 if 语句中,即

if (breakpoint.is("medium")) {
...
}

关于javascript - 仅在移动设备上使用某些 javascript 代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55641765/

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