javascript 在移动视口中隐藏或删除 div 类?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20819487/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Hide or remove a div class at mobile viewport?
提问by ben.kaminski
First and foremost, I am very aware of CSS media queries. My problem is this: When you have div classes stacked in one div; Example:
首先,我非常了解 CSS 媒体查询。我的问题是:当您将 div 类堆叠在一个 div 中时;例子:
<div class="class1 class2"></div>
And you want to remove "class2" @media (max-width: 768px) Creating an output of:
你想删除“class2”@media (max-width: 768px) 创建一个输出:
<div class="class1"></div>
...once the 768px threshold has been reached.
...一旦达到 768 像素阈值。
So far I have come up with nothing other than this non-functional code:
到目前为止,除了这个非功能性代码之外,我什么也没有想出:
<script>
jQuery(document).resize(function () {
var screen = $(window)
if (screen.width < 768) {
$(".class2").hide();
}
else {
$(".class2").show();
}
});
</script>
I am really having a hard time finding an answer that works for this. I do not want to block the entire div's contents! Just remove one of two classes.
我真的很难找到适用于此的答案。我不想阻止整个 div 的内容!只需删除两个类之一。
回答by adeneo
I'm not sure I get this, but are you just trying to toggle a class?
我不确定我是否明白这一点,但您只是想切换课程吗?
$(window).on('resize', function () {
$('.class1').toggleClass('class2', $(window).width() < 768);
});
jQuery has addClass(), removeClass()and toggleClass()methods readily available.
jQuery 具有现成的addClass()、removeClass()和toggleClass()方法。
Note that screen
is already defined in javascript.
请注意,screen
它已在 javascript 中定义。
回答by Josh Beam
Use the jQuery .removeClass()method:
使用 jQuery .removeClass()方法:
$(document).resize(function () {
var screen = $(window);
if (screen.width < 768) {
$('div').removeClass('class2');
} else {
$('div').addClass('class2');
}
OR:
或者:
screen.width < 768 ? $('div').removeClass('class2') : $('div').addClass('class2');
});
回答by RustyToms
$(".class2").removeClass("class2")
And you should listen to the window
not the document
, so you can modify your code to the following:
您应该听听window
not the document
,因此您可以将代码修改为以下内容:
<script>
jQuery(window).resize(function () {
var screen = $(window)
if (screen.width < 768) {
$(".class2").removeClass("class2");
}
else {
$(".class1").addClass("class2");
}
});
</script>
Of course, this will only toggle class2
properly if you want all class1
elements to have class2
when the screen width is greater than 768. If you don't want that, just add an extra class that has no effect, but acts as a flag indicating which elements should have class2
.
当然,只有当屏幕宽度大于 768 时,class2
如果您希望所有class1
元素都具有,这只会正确切换。class2
如果您不希望那样,只需添加一个没有效果的额外类,但充当指示哪些元素的标志应该有class2
。