我有一個(gè)帶有. hover屬性的按鈕元素,并且我需要在頁面安裝后立即顯示懸停動(dòng)畫。我怎么能把一個(gè)類屬性到一個(gè)按鈕上,然后又把它取消呢?
我在考慮使用setTimeout,但是它不能正常工作。我的代碼來自這個(gè)代碼筆:https://codepen.io/lucasfads/pen/QWwjGjv
<a href="#" class="button" id="specialButton">
<span class="icon">?</span>
<span class="text">Hakuna Matata</span>
</a>
mounted() {
document.getElementById("specialButton").classList.add("expanded");
setTimeout(() => {
document.getElementById("specialButton").classList.remove("expanded");
}, 3000);
}
.button {
background-color: #099;
color: white;
text-decoration: none;
border-radius: 60px;
height: 32px;
display: inline-flex;
align-items: center;
overflow:hidden;
width: auto;
max-width: 32px;
transition: max-width 0.5s;
}
.button:hover,
.button .expanded {
max-width: 300px;
}
.icon {
font-family: "Font Awesome 5 Free";
font-size: 16px;
margin-right: 15px;
padding: 0px 8px;
display: flex;
align-items: center;
}
.text {
white-space: nowrap;
padding-right: 15px;
}
請(qǐng)看看下面的代碼片段(Vue方式,不需要獲取元素):
new Vue({
el: '#demo',
data() {
return {
initBtn: true
}
},
mounted() {
setTimeout(() => this.initBtn = false, 3000);
}
})
.button {
background-color: #099;
color: white;
text-decoration: none;
border-radius: 60px;
height: 32px;
display: inline-flex;
align-items: center;
overflow:hidden;
width: auto;
max-width: 32px;
transition: max-width 0.5s;
}
.button:hover,
.button.expanded {
max-width: 300px;
}
.icon {
font-family: "Font Awesome 5 Free";
font-size: 16px;
margin-right: 15px;
padding: 0px 8px;
display: flex;
align-items: center;
}
.text {
white-space: nowrap;
padding-right: 15px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="demo">
<a href="#" class="button" :class="initBtn && 'expanded'">
<span class="icon">?</span>
<span class="text">Hakuna Matata</span>
</a>
</div>
應(yīng)該是. button.expanded not。按鈕。擴(kuò)大
除此之外,看Jaromanda X的評(píng)論,我同意在Vue中使用直接DOM操作是一個(gè)不好的指標(biāo)。
另一個(gè)想法——默認(rèn)擁有這個(gè)類,以后再刪除它可能會(huì)更有效。否則你掛載,添加類,刪除類- 3 DOM操作。相反,你可以只安裝,刪除類2 DOM操作。