[英]Jquery, Remove class when width screen is 1050px
这是我正在使用的JS代码:
$("document").ready(function($){
var nav = $('#menu2');
$(window).scroll(function () {
if ($(this).scrollTop() > 90) {
nav.addClass("f-nav");
} else {
nav.removeClass("f-nav");
}
});
但我似乎无法将其纳入我的代码中。
function checkWidth(init){
/*If browser resized, check width again */
if ($(window).width() < 514) {
$('html').addClass('mobile');
}
else {
if (!init) {
$('html').removeClass('mobile');
}}}$(document).ready(function() {
checkWidth(true);
$(window).resize(function() {
checkWidth(false);
});
我想要的是当.f-nav
添加到#menu2
,当屏幕<1050
,应删除该类。
要将html
更改为#menu2
,只需将其替换为另一个。 在这方面,jQuery非常简单
if ($(window).width() < 514) {
$('#menu2').addClass('f-nav');
} else {
$('#menu2').removeClass('f-nav');
}
这最好通过媒体查询实现
@media screen and (max-width:1050px){
.mobile{
/* will only apply on devices narrower than 1050px */
}
}
编辑:也可以在现代浏览器中使用javascript进行媒体查询
if (matchMedia) { // check if browser supports media queries from JavaScript
var mq = window.matchMedia("(max-width: 1050px)");
WidthChange(mq);
// every time width changes, check the media query
mq.addListener(function WidthChange(mq){
if(mq.matches){
//we are in a mobile size browser
$('#menu2').addClass('mobile');
$('#menu2').removeClass('f-nav');
} else{
// desktop browser
$('#menu2').addClass('f-nav');
$('#menu2').removeClass('mobile');
}
});
}
当您在比断点大的屏幕上加载网站时,脚本将无法工作,因为您需要重新计算屏幕大小(在这种情况下刷新页面)。 你需要在调整大小时获得屏幕的宽度。 使用resize()方法,在其中放置测试条件,并将类分配给元素。 参考帮助您: http : //api.jquery.com/resize/
如果你想在JS中更改div的类,你可以这样做:
document.getElementById("#YourId").className = "YourNewClass"
它只会改变你的类属性:-)
像这样,您还可以检查使用哪个类,并执行您想要执行的操作。
编辑感谢Olaf Dietsche:这必须是一个重复的帖子,这里可以是你的答案: jquery,当窗口宽度改变时添加/删除类
有几种方法可以做到这一点:
看到它在行动: 小提琴
$(window).resize(function() {
if ($(window).width() < 1050) {
$selector.removeClass('my-class');
} else {
$selector.addClass('my-class');
}
}).resize(); // trigger resize event initially
不要忘记:你不必在$(document).ready
放置$(window).resize
。
看到它在行动: 小提琴
这里解释了这种技术: http : //www.senaeh.de/media-query-variablen-javascript-auslesen/
基本原则:使用CSS伪元素设置变量并使用javascript获取它。
即使使用了媒体查询,如果必须使用Javascript,这种解决方法也很好,因为您不必两次声明断点。
CSS
@media screen and (max-width: 1050px) {
body:after {
content: 'tablet';
display: none;
}
}
使用Javascript
var mode = window.getComputedStyle(document.body,':after').getPropertyValue('content');
请注意:IE <9不支持getComputedStyle
。 你必须使用像这样的polyfill。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.