简单的计数器将数字的颜色更改为红色(减少)绿色(增加)以某种方式难以获得零黑色



我只是在经历一些简单的js项目,不知何故卡在这里。 我有一个计数器,它有两个按钮,可以将显示的值减少一个或减少一个。

负值红色 - 正值绿色

零应该是黑色的

我已经考虑过在范围之外创建另一个跟踪计数的变量,但它也没有完全起作用。

感谢您的任何帮助

const counter = document.getElementById('counter');
const buttonDown = document.querySelector('.prevBtn');
const buttonUp = document.querySelector('.nextBtn');

buttonDown.addEventListener('click', function() {
console.log(counter.textContent == 0);
console.log('test')
if (counter.textContent == 0) {
counter.style.color = 'black';
}
counter.textContent--;
if (counter.textContent < 0 ) {
counter.style.color = 'red';
} 
})
buttonUp.addEventListener('click', function() {

if (counter.textContent == 0) {
counter.style.color = 'orange';
}
counter.textContent++;
if (counter.textContent > 0 )
counter.style.color = 'green';

})

更改如下

if (parseInt(counter.textContent) == 0) {

现在我明白了你需要什么:

const counter = document.getElementById('counter');
const buttonDown = document.querySelector('.prevBtn');
const buttonUp = document.querySelector('.nextBtn');
function updateCounter(change) {
var counterNumericValue = Number(counter.textContent)+change;
counter.textContent = counterNumericValue;
counter.style.color=(counterNumericValue>0)?"green":(counterNumericValue<0):"red":"black";
}
buttonDown.addEventListener('click', function() {
updateCounter(-1);
});
buttonUp.addEventListener('click', function() {
updateCounter(1);
});

以下是您的代码更正:

const counter = document.getElementById('counter');
const buttonDown = document.querySelector('.prevBtn');
const buttonUp = document.querySelector('.nextBtn');
buttonDown.addEventListener('click', function() {
var counterNumericValue = Number(counter.textContent);
if(counterNumericValue == 0)
counter.style.color = 'black';
else {
counterNumericValue--;
counter.textContent = counterNumericValue;
counter.style.color = 'red';
} 
});
buttonUp.addEventListener('click', function() {
var counterNumericValue = Number(counter.textContent);
counterNumericValue++;
counter.textContent = counterNumericValue;
counter.style.color = 'green';
});

最新更新