2017-05-28 102 views
0

我在尋找一種方式來得到這個工作:按鈕,隱藏背景動畫

我想有一個網站,它控制的背景動畫的按鈕。它應該通過點擊「淡出」(直接,無延遲)整個背景動畫,但通過再次點擊,它應該「淡入」。

我嘗試這樣做:

if (document.querySelector('.Welle').style.display == 'none'){ 
 
    document.querySelector('.Welle').style.display = 'block'; 
 
} 
 
else { 
 
    document.querySelector('.Welle').style.display = 'none'; 
 
}
<a type="button" value="Klicken um Hintergrundanimation zu beenden" onclick="backgroundbutton()" style="text-decoration: none;"> 
 
    <button> 
 
     Hintergrund 
 
    </button> 
 
</a>

,但它沒有工作,我究竟做錯了什麼?有人能糾正我嗎?

非常感謝

+0

要添加此功能,您應該給DIV一個'class'。當'class'存在時,你的css中的'class'將會淡入,當'class'不存在時淡出這個項目。在你的JS中,當點擊按鈕時,你將添加和刪除'class'。 –

+0

我可能會誤會你,但我已經在和班級一起工作了。 Welle定義了一個類元素。 – QuackBrick

+0

您正在使用'.Welle''類'來選擇DOM中的背景,但沒有爲該'class'定義樣式。你應該把樣式添加到'.Welle'中,然後刪除/添加'class'到你用JS點擊的項目。 –

回答

0

var Welle = document.querySelector('.Welle'); 
 

 
function backgroundbutton() { 
 
    // if the display is "none", we return "block", else we return "none" 
 
    var dp = (Welle.style.display == 'none') ? 'block' : 'none'; 
 
    Welle.style.display = dp; 
 
}
body { margin: 0; padding: 0 } 
 

 
.Welle { 
 
    width: 100%; 
 
    height: 100vh; 
 
    background: yellow url('http://wallpapercave.com/wp/pwQMS6f.jpg') no-repeat; 
 
    background-size: cover; 
 
    z-index: -1; 
 
    display: block; 
 
    position: fixed; 
 
    top: 0; 
 
    left: 0; 
 
}
<div class="Welle"></div> 
 
<button onclick="backgroundbutton()">Hintergrund</button>

+0

非常感謝你,工作得很好,你解決了我的問題。 – QuackBrick

+0

歡迎您,我很高興它有幫助,享受編碼! –

1

試試這個:

function backgroundbutton() { 
 
    if (document.querySelector('.Welle').style.display == 'none'){ 
 
    document.querySelector('.Welle').style.display = 'block'; 
 
    } 
 
    else { 
 
    document.querySelector('.Welle').style.display = 'none'; 
 
    } 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script> 
 
<input type="button" value="Hintergrund" onclick="backgroundbutton();" /> 
 
<div class="Welle">test</div>