jQuery触发某个窗口宽度以上的函数 [英] jQuery trigger function above a certain window width
问题描述
我正在尝试写一些jQuery,遇到很多问题。我需要一个功能始终可用,并且一个功能在用户窗口大于设定宽度时可用。这里是我的函数,它们都运行在 jQuery(document).ready(function($){
函数下拉菜单,只应该在窗口大于设定值时才会发生;
//桌面用户的下拉代码
函数largeDropDown(){
$('#nav ul li')。hover(
// open
function(){$(this).find('ul')。 stop()。slideDown(300);},
//关闭
function(){$(this).find('ul')。stop()。slideUp(300);}
$;
}
这个可以随时使用,
//小屏幕的下拉代码
$('a.menu_trigger')。click(openMenu);
function openMenu(e){
e.preventDefault();
if($(this).next(' ul')。hasClass('open_menu')){
$(this).next('ul')。slideUp(300).removeClass('open_menu');
$(this).html(& darr;);
} else {
$(this).next('ul')。slideDown(300).addClass('open_menu');
$(this).html(& uarr;);
}
}
使用CSS媒体查询,当窗口超过768px时,code> a.menu_trigger 被隐藏。这样jQuery将不会做任何事情(至少这是我试图让这个工作!)
所以,我想知道如何做第一个函数在768px以上工作,以及如何在调整窗口大小时调用此功能。任何帮助将是伟大的!谢谢。
您可以通过执行以下操作绑定窗口大小调整事件:
<$ p $ ('resize',function(event){
//在这里做的东西
});
您可以通过以下操作获取窗口大小:
var windowWidth = $(window).width();
if(windowWidth> 768){
//在这里做的东西
}
请小心你在窗口中绑定的大小事件。当用户自然调整浏览器大小时,最终可能会执行数十次。沉重的代码会导致糟糕的用户体验。
I'm having a lot of problems with some jQuery I'm trying to write. I need one function to be available all the time, and one function to be available when the users window is greater than a set width. Here are my functions, both running in jQuery(document).ready(function($){
Function for drop down menus, should only happen when the window is larger than set amount;
//the dropdown code for desktop users
function largeDropDown(){
$('#nav ul li').hover(
//open
function(){ $(this).find('ul').stop().slideDown(300); },
//close
function(){ $(this).find('ul').stop().slideUp(300); }
);
}
And this one is available all the time, although it would be nice to know how to make this one conditional to the screen size also.
//the dropdown code for smaller screens
$('a.menu_trigger').click(openMenu);
function openMenu(e){
e.preventDefault();
if($(this).next('ul').hasClass('open_menu')){
$(this).next('ul').slideUp(300).removeClass('open_menu');
$(this).html("↓");
} else {
$(this).next('ul').slideDown(300).addClass('open_menu');
$(this).html("↑");
}
}
Using CSS media queries, the a.menu_trigger
is hidden when the window is over 768px. That way the jQuery won't do anything (at least that's my attempt at getting this to work!)
So, I'd like to know how to make the first function work above 768px, and also how to call this functionality on a window resize. Any help would be great! Thanks.
You can bind window resize events by doing:
$(window).on('resize', function(event){
// Do stuff here
});
You can get the window size by doing:
var windowWidth = $(window).width();
if(windowWidth > 768){
// Do stuff here
}
Here is a jsfiddle to see it all in action.
Be careful what you bind in your window resize events. It can end up being executed dozens of times when a user naturally resize the browser. Heavy code will result in a poor user experience.
这篇关于jQuery触发某个窗口宽度以上的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!