2016-07-14 22 views
0

我是網站建設的初學者,每次按下按鈕時都想創建一個動畫。所以我試着先在CSS上做,但意識到它不能單獨完成,所以我將JS併入我的代碼仍然無法工作。這個想法是,當我按下按鈕「Filter」時,元素中的菜單「.filter」就會關閉,所以我嘗試添加一個動畫來移動邊距,這不起作用。我該如何做這項工作?我在使用JS和CSS製作的動畫時遇到了麻煩

function btnFilter() { 
 
    document.getElementByClass(".filter").style.WebkitAnimation = "filter-animation"; 
 
    document.getElementByClass(".filter").style.animation = "filter-animation"; 
 
}
.filter { 
 
    display: none; 
 
    position: relative; 
 
    border-radius: 8px; 
 
    border-bottom: 1px solid #ffffff; 
 
    border-left: 1px solid #ffffff; 
 
    border-right: 1px solid #ffffff; 
 
    margin-top: -57px; 
 
} 
 
@-webkit-keyframes filter-animation { 
 
    from { 
 
    margin-top: -57px; 
 
    display: none; 
 
    } 
 
    to { 
 
    margin-top: 30px; 
 
    display: flex; 
 
    } 
 
} 
 
@keyframes filter-animation { 
 
    from { 
 
    margin-top: -57px; 
 
    display: none; 
 
    } 
 
    to { 
 
    margin-top: 30px; 
 
    display: flex; 
 
    } 
 
}
<button onclick="btnFilter()">Filter</button> 
 
<div class="filter"> 
 
    <p>filter</p> 
 
    <form class="drpdwn-1"> 
 
    <p>Price range:</p> 
 
    <select value="Price Range"> 
 
     <option>$0 - $50</option> 
 
     <option>$50 - $100</option> 
 
     <option>> $100</option> 
 
    </select> 
 
    </form> 
 
</div>

+1

注意它應該是'getElementsByClassName方法()',而不是'getElementByClass()',所以你需要也返回元素的數組循環遍歷數組,並逐個更新'style'。將類應用到元素並將關鍵幀動畫放在該類上也會更容易。 –

回答

0
function btnFilter() { 
    document.getElementsByClassName(".filter").style.WebkitAnimation = "filter-animation"; 
    document.getElementsByClassName(".filter").style.animation = "filter-animation"; 
} 

使用getElementsByClassName('.className')...

+1

實際上它是'getElementsByClassName()'並避免參數中的'.'。所以你的代碼是無效的。 請避免急於先回應並測試您的代碼。 – RDardelet

0

您只能使用CSS,但您需要切換一個css類來每次都爲動畫按鈕設置動畫。

下面是一個例子:

var el = document.querySelector(".button"); 
 

 
el.addEventListener('click', function() { 
 
    if(!el.classList.contains("animate")) { 
 
    el.classList.add("animate"); 
 
    } else { 
 
    el.classList.remove("animate"); 
 
    } 
 
});
.button { 
 
    font-weight: bold; 
 
    font-size: 1.2em; 
 
    color: white; 
 
    background-color: #777; 
 
    padding: 0.7em 2em; 
 
    border: 0; 
 
    margin: 1em auto 0; 
 
    border-radius: 3px; 
 
    box-shadow: 0 3px 0 #444; 
 
    display: block; 
 
    cursor: pointer; 
 
    appearance: none; 
 
    
 
    transition: transform 1.5s ease; 
 
} 
 

 
.animate { 
 
    transform: translateY(50px); 
 
}
<button class="button">Click me</button>

相關問題