当前位置: 动力学知识库 > 问答 > 编程问答 >

javascript - jQuery function on resize and on load without copy/pasting

问题描述:

I have the following piece of jQuery that checks the width of the browser on load, and runs accordingly. But to make sure the div keeps the right size when the browser-width is changed, I have placed the same piece of code in $(window).resize(function() {..});.

This seems very weird and unnecessary, so I'm wondering how I can place the code only once and have it run on both .resize and on load.

var windowWidth = $(window).width();

if(windowWidth > 768 && windowWidth < 1223){

$('.banner_image').show();

$('.banner_image').height($('.banner .span3').height());

$('.banner .span12 img').hide();

}

else {

$('.banner_image').hide();

$('.banner .span12 img').show();

}

$(window).resize(function() {

var windowWidth = $(window).width();

if(windowWidth > 768 && windowWidth < 1223){

$('.banner_image').show();

$('.banner_image').height($('.banner .span3').height());

$('.banner .span12 img').hide();

}

else {

$('.banner_image').hide();

$('.banner .span12 img').show();

}

});

网友答案:

You can trigger the event after binding the event:

$(window).resize(function() {
var windowWidth = $(window).width();
if(windowWidth > 768 && windowWidth < 1223){
    $('.banner_image').show();
    $('.banner_image').height($('.banner .span3').height());
    $('.banner .span12 img').hide();                
}
else {
    $('.banner_image').hide();
    $('.banner .span12 img').show();
}).resize();//resize to trigger on load

Working Demo

网友答案:

Just store the function in a variable and execute it everytime you want to:

$(window).load(function() {
   wFunc();
});    

$(window).resize(function() {
   wFunc();
});   

var wFunc = function() {
   var windowWidth = $(window).width();
   if(windowWidth > 768 && windowWidth < 1223){
    $('.banner_image').show();
    $('.banner_image').height($('.banner .span3').height());
    $('.banner .span12 img').hide();            
   }
   else {
    $('.banner_image').hide();
    $('.banner .span12 img').show();
   }
}
分享给朋友:
您可能感兴趣的文章:
随机阅读: