[英]How do I add/remove or toggle classes based on the screen width?
Forgive me if this has been answered as I am struggling to find a similar scenario (which I find bazaar as I am sure this is a common script to run).如果这个问题已经得到解答,请原谅我,因为我正在努力寻找类似的场景(我找到了 bazaar,因为我确信这是一个可以运行的通用脚本)。
Basically, I would like to toggle or even add and remove a class based on the screen width.基本上,我想根据屏幕宽度切换甚至添加和删除 class 。 Below is my attempt at a script, where the eventlistener is working based on the colsole.log but I can't get the function to toggle the classes.下面是我对脚本的尝试,其中 eventlistener 基于 colsole.log 工作,但我无法让 function 切换类。
Basically, I would like to:基本上,我想:
turn class.mobile on and.desktop off for all elements that have the class.responsive, when the view width is less than 700px当视图宽度小于 700 像素时,为所有具有 class.responsive 的元素打开class.mobile 和关闭桌面
And then turn class.desktop on and.mobile off for all elements that have the class.responsive, when the view width is greater than 701px.然后当视图宽度大于 701px 时,为所有具有 class.responsive 的元素打开 class.desktop和.mobile关闭。
My attempt:我的尝试:
window.addEventListener("resize", function() {
var w = window.innerWidth;
var responsiveDiv = document.querySelectorAll('.responsive')[0];
//for (var i = 0; i < responsiveDiv.resize; i++)
{
//responsiveDiv[i].addEventListener('resize', function() {
if (w < 700) {
//responsiveDiv.classList.remove('desktop');
responsiveDiv.classList.remove=("desktop");
responsiveDiv.classList.add("mobile");
console.log("desktop Remove");
} else {
responsiveDiv.classList.add("mobile");
console.log("mobile removed");
} }
});
(The parts that are commented out, are parts that I think need to go the script but they end up breaking the console log, probably because the syntax is wrong. ) (注释掉的部分是我认为需要 go 脚本的部分,但它们最终破坏了控制台日志,可能是因为语法错误。)
Also if what I am trying to achieve is not the industry standard way of doing it, I am more than happy to be advised alternative ways to achieve the same thing.此外,如果我想要实现的不是行业标准的实现方式,我很乐意被告知实现相同目标的替代方法。
I have used the forEach method instead of a loop you can interchange that.我使用了 forEach 方法而不是循环,你可以互换它。
There were few mistakes in your code that are as follows:您的代码中几乎没有错误,如下所示:
Check below I have corrected the code Hope this solved your problem.检查下面我已经更正了代码希望这可以解决您的问题。
window.addEventListener("resize", function() { var w = window.innerWidth; console.log(w) var responsiveDiv = document.querySelectorAll('.responsive'); responsiveDiv.forEach((element) => { console.log(element) if(w < 700) { element.classList.remove("desktop"); element.classList.add("mobile"); console.log("desktop Remove"); } else { element.classList.remove("mobile"); element.classList.add("desktop"); console.log("mobile removed"); } }) });
.responsive{min-width: 100vw; min-height: 100vh;}
<div class='responsive'>1</div> <div class='responsive'>2</div> <div class='responsive'>3</div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.