2015-08-29 174 views
1

我在頁面上有一個按鈕,標籤爲「黑暗主題」。我想這樣做,這個按鈕改變了背景的效果。當你點擊它時,我希望它具有彩虹效果,當你再次點擊它時,我希望它回到黑暗的主題。我附上相關的代碼如下:如何從點擊開始動畫

body { 
 
    margin: 0px; 
 
    padding: 0px; 
 
    overflow-y: scroll; 
 
    font-family: Helvetica; 
 
    font-size: 18px; 
 
    background-color: #bdbdbd; 
 
    background-color: #45CEEF; 
 
    -webkit-animation: pulse 1s infinite alternate; 
 
} 
 

 
h3 { 
 
    font-weight: bold; 
 
    text-decoration: underline; 
 
} 
 
h2 { 
 
    font-weight: bold; 
 
    text-decoration: underline; 
 
} 
 

 
/*Light Switch*/ 
 

 
label { 
 
    display: block; 
 
    height: 25px; 
 
    width: 100px; 
 
    background: white; 
 
    text-align: center; 
 
    font: 14px/25px Helvetica, Arial, sans-serif; 
 
    margin: 20px 0; 
 
    position: absolute; 
 
    color: black; 
 
    transition: background 0.2s ease-out, color 0.2s ease-out; 
 
} 
 
label:hover { 
 
    background-color: #099; 
 
    color: white; 
 
    cursor: pointer; 
 
    transition: background-color 0.1s ease-in, color 0.1s ease-in; 
 
} 
 
input#lightswitch { 
 
    position: fixed; 
 
    top: -9999px; 
 
    left: -9999px; 
 
} 
 
input#lightswitch + .content { 
 
    color: black; 
 
    transition: background-color 0.5s ease-out, color 0.5s ease-out; 
 
} 
 
/*Switched Off*/ 
 

 
input#lightswitch:checked + .content { 
 
    background-color: #222; 
 
    color: #D3D3D3; 
 
    transition: background-color 0.5s ease-in, color 0.5s ease-in; 
 
} 
 
@-webkit-keyframes pulse { 
 
    0% { 
 
    background-color: #45CEEF; 
 
    } 
 
    25% { 
 
    background-color: #FFF5A5; 
 
    } 
 
    50% { 
 
    background-color: #FFD4DA; 
 
    } 
 
    75% { 
 
    background-color: #99D2E4; 
 
    } 
 
    100% { 
 
    background-color: #D8CAB4; 
 
    } 
 
}
<link rel="stylesheet" type="text/css" href="bda.css"> 
 

 
<body class="body"> 
 
    <label for="lightswitch">Dark Theme</label> 
 
    <input type="checkbox" id="lightswitch" /> 
 
</body>

我的代碼:https://jsfiddle.net/em07jce9/1/

+1

請如何*有關*碼直接在你的問題。 – nnnnnn

+0

該動畫適用於webkit,因此它不會在Firefox上顯示 – MinusFour

回答

3

當單擊該按鈕時,使用JavaScript的CSS類添加到您想要的動畫元素。在您的樣式表中,將動畫附加到該特定的類。

CSS:

.body.animated { 
    -webkit-animation: pulse 1s infinite alternate; 
} 

JS:

$(function() { 
    $('button').on('click', function() { 
    $('.body').addClass('animated'); 
    }); 
}); 

如果你使用一個複選框爲切換,使用change事件:

$(function() { 
    $('input#lightswitch').on('change', function() { 
    $('.body').toggleClass('animated'); 
    }); 
});