本文介绍了似乎无法获得jquery resize事件来处理Modernizr媒体查询功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在以下函数上激活resize事件:

I'm trying to activate a resize event on the following function:

$(function() {
if (Modernizr.mq('only screen and (min-width: 1140px)')) {
$('div#ss1').html('<div>[snip]</div>');
$('div#ss1').append('<div><gcse:searchbox-only></gcse:searchbox-only></div>');
  } 
if (Modernizr.mq('only screen and (max-width: 1139px)')) {
$('div#ss2').html('<div>[snip]</div>');
$('div#ss2').append('<div><gcse:searchbox-only></gcse:searchbox-only></div>');
  } 
});

我想为它添加一个调整大小的侦听器。基于我将第一行更改为 $(window).resize(function()但随后整个函数停止工作。

I wanted to add a resize listener to it. Based on http://api.jquery.com/resize/ I changed the first line to $(window).resize(function() but then the whole function stopped working.

我做错了什么?谢谢。

更新:基于此保罗爱尔兰我在我的plugins.js中添加了smartresize。我将函数调用从 $(function()更改为 $(window).smartresize(function()并且它停止工作。将其更改回 $(function()并再次运行。为什么我不能向这个吸盘添加任何类型的resize事件监听器?: - )

UPDATE: Based on this Paul Irish post I added smartresize to my plugins.js. I changed the function call from $(function() to $(window).smartresize(function() and it stopped working. Changing it back to $(function() and it worked again. Why can't I add a resize event listener of any type to this sucker? :-)

推荐答案

要理解的关键点这是 $(function(){})正在做什么。在文档准备好之前,它内部的代码没有执行。将代码放入其中相当于放入代码在此:

The key point to understand here is what $(function() {}) is doing. The code inside of it isn't executing until the document is ready. Putting code in it is equivalent to putting code in this:

$(document).ready(function () { 
    //here 
})

您想将调整大小事件放在 $(function(){})中,如下所示:

You want to put your resize event inside of $(function() {}), like this:

function checkMq() {
    if (Modernizr.mq('only screen and (min-width: 1140px)')) {
        $('div#ss1').html('<div>[snip]</div>');
        $('div#ss1').append('<div><gcse:searchbox-only></gcse:searchbox-only></div>');
    } 
    if (Modernizr.mq('only screen and (max-width: 1139px)')) {
        $('div#ss2').html('<div>[snip]</div>');
        $('div#ss2').append('<div><gcse:searchbox-only></gcse:searchbox-only></div>');
    } 
}

$(function() {
    // the call to checkMq here will execute after the document has loaded
    checkMq();

    $(window).resize(function() {
        // the call to checkMq here will execute every time the window is resized
        checkMq();
    });

    // you can add other listeners here click, hover, etc.  
});

如果你只有 $(窗口).resize(function() {})不使用 $(function(){}),它将无法正常工作,因为该文档尚未准备就绪但是,也没有准备好添加任何事件监听器。

If you just have the $(window).resize(function() {}) without using $(function() {}), it won't work because the document isn't ready to be worked on yet, nor is it ready to have any event listeners added.

这篇关于似乎无法获得jquery resize事件来处理Modernizr媒体查询功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-25 05:22