如何在单击另一个按钮时将动态类添加到多个动态按钮中



我正在开发一个nuxt.js web应用程序,我有一个静态按钮和多个动态按钮,单击静态按钮后,我想为每个动态按钮添加类。

使用下面的代码,我可以将类添加到按钮中,但它只在第一个按钮上工作,在其余按钮上,类被动态添加。

<button  @click="scrollToDiv()" class="btn btn-block btn-primary py-2 text-center rounded" style="background: #1f7ae0; border: #1f7ae0;">

下面是多个动态按钮

<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)
}

我想在点击静态按钮时为每个动态按钮添加动态CSS

.glow {
color: #fff;
background: linear-gradient(40deg, #2031ffa1, #05ff75cf) !important;
border-radius: 12px !important;
box-shadow: 5px 5px #ff922e !important;
}

当您使用nuxt.js时,我假设是vue.js解决方案。

  1. 在数据部分追加切换值
data () {
return {
...
glow: false,
...
}
}
  1. 在每个动态按钮中添加类绑定。当glow datatrue时,:class="{ glow }"属性绑定class name glow
<button id="enroll" class="btn btn-primary btn-block text-center rounded" :class="{glow}" style="background: #2685ef;border: 2px solid #2685ef;">Buy Now</button>
<button id="enroll" class="btn btn-primary btn-block text-center rounded" :class="{glow}" style="background: #2685ef;border: 2px solid #2685ef;">Buy Now</button>
<button id="enroll" class="btn btn-primary btn-block text-center rounded" :class="{glow}" style="background: #2685ef;border: 2px solid #2685ef;">Buy Now</button>
  1. 仅控制辉光数据。它会影响每个按钮的类名
scrollToDiv() {
this.glow = true
setTimeout(() => {
this.glow = false
}, 2000)
}
  1. 在数据中设置timeout id(如组件中的全局变量(。在原始代码中,超时idscrollTimeoutscrollToDiv中的局部变量,clearTimeout没有意义。每次执行scrollToDiv都会在函数范围内生成新的scrollTimenout
data () {
return {
...
glow: false,
timer: null,
...
}
},
...
methods: {
...
scrollToDiv() {
this.glow = true
clearTimeout(this.timer)
this.timer = setTimeout(() => {
this.glow = false
}, 2000)
}
}
...

元素的id应该是唯一的,所以当您使用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)
}

最新更新