javascript - jQuery custom toggle function? - Stack Overflow

I'm trying to make a custom jQuery toggle function. Right now, I have 2 separate functions, lights

I'm trying to make a custom jQuery toggle function. Right now, I have 2 separate functions, lightsOn and lightsOff. How can I bine these functions to make them toggle (so I can just link to one function)?

function lightsOn(){
 $('#dim').fadeOut(500,function() {
   $("#dim").remove();
 });
};

function lightsOff(){
 $('body').append('<div id="dim"></div>');
 $('#dim').fadeIn(250);
};

I'm trying to make a custom jQuery toggle function. Right now, I have 2 separate functions, lightsOn and lightsOff. How can I bine these functions to make them toggle (so I can just link to one function)?

function lightsOn(){
 $('#dim').fadeOut(500,function() {
   $("#dim").remove();
 });
};

function lightsOff(){
 $('body').append('<div id="dim"></div>');
 $('#dim').fadeIn(250);
};
Share Improve this question asked Dec 21, 2011 at 3:56 hao_maikehao_maike 3,0496 gold badges29 silver badges31 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 6
function toggleLights()
{
    var $dim = $('#dim');
    if ($dim.length)
    {
        $dim.fadeOut(500, function ()
        {
            $dim.remove();
        });
    }
    else
    {
        $dim = $('<div/>', {id: 'dim'});
        $('body').append($dim);
        $dim.fadeIn(250);
    }
}

Demo: http://jsfiddle/mattball/hxL8s/

function toggleLights(){
    if ($("body").has("#dim")) {
        $('#dim').fadeOut(500, function() {
           $("#dim").remove();
        });
    } else {
        $('body').append('<div id="dim"></div>');
        $('#dim').fadeIn(250);
   }
}

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744276035a4566335.html

相关推荐

  • javascript - jQuery custom toggle function? - Stack Overflow

    I'm trying to make a custom jQuery toggle function. Right now, I have 2 separate functions, lights

    7天前
    20

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信