开发者

Merge 2 jQuery functions

I have 2 jQuery functions that basicly are written the same except for their 1st lines:

$(document).ready(function() {
 var h = $(window).height();
 var w = $(window).width();
 $('#foo').css({'height' : h});
 $('#foo').css({'width' : w});
});

$(window).resize(function() {
 var h = $(window).height();
 var w = $(window).width();
 $('#foo').css({'height' : h});
 $('#foo').css({'width' : w});
});

so I was wondering if its possible to merge them开发者_如何转开发 into 1 some how?

As always thanks in advance.


You can trigger the resize event manually:

$(function() { // shortcut for $(document).ready(function() {...});
    $(window).resize(function() {   // bind the handler
        $('#foo').css({
            'height': $(window).height(),
            'width': $(window).width()
        });
    }).resize(); // trigger the resize event
});

or create an extra function and bind it to both events:

function resizeHandler() {
    $('#foo').css({
        'height': $(window).height(),
        'width': $(window).width()
    });
}

$(document).ready(resizeHandler);
$(window).resize(resizeHandler);

Btw. $(function(){...}); is a shortcut for $(document).ready(function(){...});.


var myFunction = function() {
 var h = $(window).height();
 var w = $(window).width();
 $('#foo').css({'height' : h});
 $('#foo').css({'width' : w});
}

$(document).ready(myFunction);
$(window).resize(myFunction);


Like this:

function yourfunc() {
 var h = $(window).height();
 var w = $(window).width();
 $('#foo').css({'height' : h});
 $('#foo').css({'width' : w});
}

$(document).ready(yourfunc);
$(window).resize(yourfunc);

Another way to call it (longer but more understandable) would be:

$(document).ready(function(){
   yourfunc();
});
$(window).resize(function(){
   yourfunc();
});

Both work. Hope this helps. Cheers


create a third function

function calculateSomething(){
  var h = $(window).height();
  var w = $(window).width();
  $('#foo').css({'height' : h, 'width' : w}});
}

Then call the function

$(document).ready(calculateSomething);

$(window).resize(calculateSomething);


You could also use do:

$(window).bind('load resize', function(e){
    $('#foo').css({'width' : $(window).width(), 'height': $(window).height()});
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜