jQuery   发布时间:2022-03-30  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了似乎无法获得jquery resize事件来处理Modernizr媒体查询功能大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在尝试在以下函数上激活resize事件:

$(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>');
  } 
});

我想为它添加一个resize监听器.基于http://api.jquery.com/resize/我将第一行更改为$(window).resize(function()但是整个函数停止工作.

我究竟做错了什么?谢谢.

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

解决方法

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

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

你想把你的resize事件放在$(function(){})里面,如下所示:

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(){}),它将无法工作,因为该文档尚未准备就绪,也不是准备好添加任何事件监听器.

大佬总结

以上是大佬教程为你收集整理的似乎无法获得jquery resize事件来处理Modernizr媒体查询功能全部内容,希望文章能够帮你解决似乎无法获得jquery resize事件来处理Modernizr媒体查询功能所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签: