2015-10-15 77 views
2

我想要一條線變成一個長方形的過渡。我想做到這一點,以便當過渡完成時,即使鼠標沒有在其上徘徊,最終狀態仍保持原位。如何維護鼠標懸停狀態?

這是我當前的代碼:

#line { 
 
    width: 300px; 
 
    height: 1px; 
 
    background-color: darkblue; 
 
    transition: height 2s; 
 
    -webkit-transition: height 2s; 
 
} 
 

 
#line:hover { 
 
    width: 300px; 
 
    height: 200px; 
 
    background-color: darkblue; 
 
}
<div id="line"></div>

+0

這絕對是一個重複問題,但是當我找到一個好的目標時,答案是'animation-fill-mode:forwards';' – TylerH

+0

@TylerH這是一個動畫。它是否也適用於轉換? – GolezTrol

+0

@GolezTrol我認爲它確實,但我不知道':hover'。無論如何,看起來OP實際上並沒有在這裏處理動畫;我將編輯該問題。 – TylerH

回答

4

我認爲最好的辦法是增加一個小的腳本,將一個類。該類仍然unhovering後:

window.addEventListener('DOMContentLoaded', function() { 
 
    document.getElementById('line').addEventListener('mouseover', function(event) { 
 
    document.getElementById('line').classList.add('activated'); 
 
    }); 
 
});
#line { 
 
    width: 300px; 
 
    height: 1px; 
 
    background-color: darkblue; 
 
    transition: height 2s; 
 
    -webkit-transition: height 2s; 
 
} 
 
#line.activated{ 
 
    width: 300px; 
 
    height: 200px; 
 
    background-color: darkblue; 
 
}
<body> 
 

 
    <div id="line"></div> 
 

 
</body>

+0

嘿,這似乎是我正在尋找的解決方案。謝謝 –

+0

相同的代碼,但使用'click'而不是'mouseover'事件。 – GolezTrol

+0

啊多謝老兄 –

0

一個取巧的辦法與CSS只得到這樣的效果:在元素上的過渡,延遲設置爲一個巨大的價值。並在懸停狀態下將其設置爲0

當您懸停時,元素更改爲懸停狀態,這種方式即可立即進行轉換。

當您取消懸停,會有一個9999s延遲開始前(當然,不是永遠真的,但沒有人會注意到)

#line { 
 
    width: 300px; 
 
    height: 10px; 
 
    background-color: darkblue; 
 
    -webkit-transition: height 1s 9999s; 
 
    transition: height 1s 9999s; 
 
} 
 
#line:hover{ 
 
    width: 300px; 
 
    height: 200px; 
 
    background-color: darkblue; 
 
    -webkit-transition-delay: 0s; 
 
    transition-delay: 0s; 
 
}
<body> 
 
    <div id="line"></div> 
 
</body>