简体   繁体   中英

I want this script to work when page load and also when resize

The site is responsive

$(window).bind('resize', function() {
    $('#drop_ul').css('width', $('#container').width());
    $('#drop_ul').css('left', $('#container').css('margin-left'));
});

$(document).ready(function(){
    $('#drop_ul').css('width', $('#container').width());
    $('#drop_ul').css('left', $('#container').css('margin-left'));
});

You can extract the logic in to its own function which you can then call under both events. Try this:

function updateUI() {
    $('#drop_ul').css({
        'width': $('#container').width(),
        'left': $('#container').css('margin-left')
    });
}

$(document).ready(function() {
    updateUI(); // on load
    $(window).on('resize', updateUI); // on window resize
});

Note that I unified the css() calls, and used the preferred on instead of bind .

Also, if the site is responsive is would be best to use CSS media queries for this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM