Javascript 在浏览器调整大小时动态添加类(视口宽度)
我有一个名为jobfilter的元素,我想根据视口宽度为其添加一个类,即,当我将浏览器调整为时,您必须监听调整大小事件Javascript 在浏览器调整大小时动态添加类(视口宽度),javascript,jquery,Javascript,Jquery,我有一个名为jobfilter的元素,我想根据视口宽度为其添加一个类,即,当我将浏览器调整为时,您必须监听调整大小事件 $( window ).resize(function() { checkPosition(); }); 这是我用来在调整大小时动态检查窗口宽度的功能,我将其包装在一个文档就绪函数中,该函数将$作为参数传递,以防止与使用$的其他javascript库发生任何冲突。例如,如果你在wordpress主题或插件中使用你的函数 JSFIDLE示例: Javascript: /*
$( window ).resize(function() {
checkPosition();
});
这是我用来在调整大小时动态检查窗口宽度的功能,我将其包装在一个文档就绪函数中,该函数将$作为参数传递,以防止与使用$的其他javascript库发生任何冲突。例如,如果你在wordpress主题或插件中使用你的函数 JSFIDLE示例: Javascript:
/*
document ready function used to prevent conflict with other javascript libraries
that use the $ parameter
*/
jQuery(document).ready(function($){
//get the window width
var winWidth = $(window).width();
//set the maxWidth
var maxWidth = 1000;
//if the window width is less than the maxWidth pixels on document loading
if(winWidth < maxWidth){//begin if then
//add the class hidden to .jobFilter
$(".jobfilter").addClass("hidden");
}//end if then
$(window).resize(function(){//begin resize event
//get the window width
var winWidth = $(window).width();
//set the maxWidth
var maxWidth = 1000;
//if the window width is less than maxWidth pixels
if(winWidth < maxWidth){//begin if then
//add the class hidden to .jobFilter
$(".jobfilter").addClass("hidden");
}
else{
//remove the class hidden
$(".jobfilter").removeClass("hidden");
}//end if then else
});//end window resize event
});//end document ready function
/*
用于防止与其他javascript库冲突的文档就绪函数
使用$parameter的
*/
jQuery(文档).ready(函数($){
//获取窗口宽度
var winWidth=$(window.width();
//设置最大宽度
var maxWidth=1000;
//如果窗口宽度小于文档加载时的maxWidth像素
if(winWidth
使用调整大小事件检查窗口是否已调整大小。使用此代码
$( window ).resize(function() {
function checkPosition() {
if (window.matchMedia('(max-width: 767px)').matches) {
//...
} else {
//...
}
}
}
希望这能帮助您$(文档).ready(函数()){
$(document).ready(function(){
DOaction(); // run function after document ready
$(window).on('resize',DOaction); // on resize window run function
});
// function to add and remove hidden class
function DOaction(){
if($(window).width() <= 1000){
$(".jobfilter").addClass('hidden');
}else{
$(".jobfilter").removeClass('hidden');
}
}
DOaction();//在文档准备就绪后运行函数
$(window).on('resize',DOaction);//on resize window运行函数
});
//用于添加和删除隐藏类的函数
函数DOaction(){
如果($(window).width()鲜为人知的事实:matchMedia
具有事件侦听器:
function handleMedia(mql) {
if (mql.matches) {
// media query matches
} else {
// media query does not match
}
}
var mql = window.matchMedia('(max-width: 767px)').addListener(handleMedia);
handleMedia(mql);
每次浏览器匹配或取消匹配媒体查询时,事件侦听器都将执行。在您的情况下,我建议手动启动处理程序(如示例所示),以确保在加载时设置正确的类
这个例子取自(虽然它隐藏得很好)。为什么不在没有Jquery的情况下使用css mediaQueries?如果你是一个英雄,只要在MDN上看一下这个,就会非常容易,完全错过了听众!
function handleMedia(mql) {
if (mql.matches) {
// media query matches
} else {
// media query does not match
}
}
var mql = window.matchMedia('(max-width: 767px)').addListener(handleMedia);
handleMedia(mql);