2 回答

TA貢獻(xiàn)1752條經(jīng)驗 獲得超4個贊
我正在開發(fā)一個 nuxt.js Web 應(yīng)用程序,我有一個靜態(tài)按鈕和多個動態(tài)按鈕,單擊靜態(tài)按鈕時我想向每個動態(tài)按鈕添加類。
使用下面的代碼,我可以向按鈕添加類,但它僅適用于第一個按鈕,其余按鈕類將動態(tài)添加。
<button @click="scrollToDiv()" class="btn btn-block btn-primary py-2 text-center rounded" style="background: #1f7ae0; border: #1f7ae0;">
下面是多個動態(tài)按鈕
<button id="enroll" class="btn btn-primary btn-block text-center rounded" style="background: #2685ef;border: 2px solid #2685ef;">Buy Now</button>
<button id="enroll" class="btn btn-primary btn-block text-center rounded" style="background: #2685ef;border: 2px solid #2685ef;">Buy Now</button>
<button id="enroll" class="btn btn-primary btn-block text-center rounded" style="background: #2685ef;border: 2px solid #2685ef;">Buy Now</button>
下面是腳本
scrollToDiv() {
document.getElementById('pricing').scrollIntoView({
behavior: 'smooth',
})
var enroll = document.getElementById('enroll')
enroll.classList.add('glow')
var scrollTimeout
clearTimeout(scrollTimeout)
scrollTimeout = setTimeout(function () {
enroll.classList.remove('glow')
}, 2000)
}
我想在單擊靜態(tài)按鈕時向每個動態(tài)按鈕添加動態(tài) CSS
.glow {
color: #fff;
background: linear-gradient(40deg, #2031ffa1, #05ff75cf) !important;
border-radius: 12px !important;
box-shadow: 5px 5px #ff922e !important;
}

TA貢獻(xiàn)1777條經(jīng)驗 獲得超3個贊
元素的 id 應(yīng)該是唯一的,因此當(dāng)您使用時,getElementById您只會獲得第一個匹配的元素。我會嘗試為這三個按鈕提供相同的類,并使用getElementsByClassName(className),這將返回一個 HTMLCollection,允許您迭代元素。所以像這樣:
scrollToDiv() {
document.getElementById('pricing').scrollIntoView({
behavior: 'smooth',
})
var elements = document.getElementsByClassName('example-classname')
for(let e of elements) e.classList.add('glow')
var scrollTimeout
clearTimeout(scrollTimeout)
scrollTimeout = setTimeout(function () {
for(let e of elements) e.classList.remove('glow')
}, 2000)
}
添加回答
舉報