2014-01-27 77 views
0

我在jQuery中有一些代碼,我想通過單擊div來製作開關動畫。這是代碼。當我測試它時,它不起作用。但是,如果我刪除第7行中的toggle = true,它只是一種方式,我無法將其關閉。通過jQuery中的If語句切換動畫

$(document).ready(function() { 
    $("#switch").click(function() { 
     var toggle = false; 
     if (toggle == false) { 
      $("#circle").css("left", "27px"); 
      $("#white_rect").attr("src", "green_rect.png"); 
      toggle = true; 
     } 
     if (toggle == true) { 
      $("#circle").css("left", "1px"); 
      $("#white_rect").attr("src", "white_rect.png"); 
      toggle = false; 
     } 
    }); 
}); 
+0

你能提供你的HTML嗎?或小提琴鏈接? –

回答

5

您需要聲明的點擊處理程序的toggle變量外...其他在每一次點擊調用變量將得到重新初始化,所以該變量的值將永遠是假的。

$(document).ready(function() { 
    //declare it here 
    var toggle = false; 
    $("#switch").click(function() { 
     if (toggle == false) { 
      $("#circle").css("left", "27px"); 
      $("#white_rect").attr("src", "green_rect.png"); 
      toggle = true; 
     //also don't use a separate if block here as it will be affected by the execution of the above if block 
     } else { 
      $("#circle").css("left", "1px"); 
      $("#white_rect").attr("src", "white_rect.png"); 
      toggle = false; 
     } 
    }); 
}); 

$(document).ready(function() { 
    //declare it here 
    var toggle = false; 
    $("#switch").click(function() { 
     if (toggle) { 
      $("#circle").css("left", "1px"); 
      $("#white_rect").attr("src", "white_rect.png"); 
     } else { 
      $("#circle").css("left", "27px"); 
      $("#white_rect").attr("src", "green_rect.png"); 
     } 
     toggle = !toggle; 
    }); 
}); 
+0

+1。怎麼樣'toggle == false'到'!toggle' –

+0

@PranavRam yes ....,那會很好 –

0

最好是嚴格分開的外觀和邏輯。所以請使用.classes,並使用<div> s代替<img>。那麼你將不需要任何狀態變量,代碼應該更簡單。

HTML

<div class="container"> 
    <div class="switch off"></div> 
</div> 

CSS

.container { 
    width:100%; height:100px; padding:40px; text-align:center; 
} 
.container .switch { 
    width:94px; height: 27px; display:inline-block; background-color:pink; cursor:pointer; 
} 
.container .switch.on { 
    background: url('http://squad.pw/tmp/img/01-on.png') no-repeat 0 0; 
} 
.container .switch.off { 
    background: url('http://squad.pw/tmp/img/01-off.png') no-repeat 0 0; 
} 

JS

$('.switch').click(function() { 

    // Do visual logic 
    $(this).toggleClass('on'); 
    $(this).toggleClass('off'); 

    // Do business logic 
    window.toggle = !window.toggle; 
}); 

這裏是FIDDLE