运行jquery函数onload和focus

时间:2014-10-07 18:51:42

标签: jquery focus onload

我有一个功能:

function skillbar() {
    $('.skillbar').each(function(){
        var percent = $(this).attr('data-percent');
        $(this).find('.skillbar-bar').delay(400).animate({width:percent},1500);
    });
}

我希望在加载页面时执行此功能。所以我这样运行:

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

但我也希望只有在关注浏览器选项卡时才能运行此功能。 我试过这个:

$(window).load(function(){
    $(window).focus(function(){
        skillbar();
    });
});

问题在于,当我在加载页面时使用.focus();时,我必须切换一次浏览器选项卡,然后才能运行。 这意味着我必须专注于窗口onload,但如果有人在另一个浏览器选项卡上呢?

demo http://jsfiddle.net/sem847un/1/

1 个答案:

答案 0 :(得分:-1)

你需要$(文件).ready(function(){ 这将启动加载功能

$(document).ready(function(){
skillbar();
function skillbar() {
    $('.skillbar').each(function(){
        var percent = $(this).attr('data-percent');
        $(this).find('.skillbar-bar').delay(400).animate({width:percent},1500);
    });
}
});