【发布时间】:2022-01-25 16:20:06
【问题描述】:
如果大于零,我想将数字的颜色设为绿色,使其变为绿色,并在低于零时变为红色,但我做不到,我不明白为什么有人可以解释
const button1 = document.querySelector('.prevBtn');
const button2 = document.querySelector('.nextBtn');
const main = document.querySelector('.main-container')
const count = document.getElementById('counter')
let counter = 0
main.addEventListener('click', e => {
if(e.target.classList.contains('nextBtn')){
counter++
html=`
<h1 class="text-uppercase">counter</h1>
<h1 id="counter"class =count">${counter}</h1>
<div class="btn-container d-flex justify-content-around flex-wrap">
<button class="btn counterBtn prevBtn text-uppercase m-2">lower count</button>
<button class="btn counterBtn nextBtn text-uppercase m-2">add count</button>
`
main.innerHTML = html
}else if(e.target.classList.contains('prevBtn')){
counter--
html=`
<h1 class="text-uppercase">counter</h1>
<h1 id="counter">${counter}</h1>
<div class="btn-container d-flex justify-content-around flex-wrap">
<button class="btn counterBtn prevBtn text-uppercase m-2">lower count</button>
<button class="btn counterBtn nextBtn text-uppercase m-2">add count</button>
`
main.innerHTML = html
}
})
if(counter > 0){
count.style.color = 'green'
} else if(counter < 0) {
count.style.color = 'red'
}
【问题讨论】:
-
您正在尝试在元素添加到页面内容之前按 ID 获取元素。
-
你也必须在活动中更新样式
-
我在监听器中做到了我尝试了很多方法但它不起作用
标签: javascript html css