Я создал этот счетчик, но хочу раскрасить id="clicks" на основе положительного или отрицательного значения, а также добавить текст на основе этого.
var clicks = 0;
function clickplus() {
clicks += 1;
document.getElementById("clicks").innerHTML = clicks;
}
var clicks = 0;
function clickless() {
clicks -= 1;
document.getElementById("clicks").innerHTML = clicks;
}
#btn_plus{
background-color: #04AA6D; /* Green */
border: none;
color: white;
padding: 15px 32px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;}
#btn_less{
background-color: red; /* Green */
border: none;
color: white;
padding: 15px 32px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;}
<body style = "background-color:#F0F0F0">
<center>
</br></br></br>
<h1>
<p style = "color:#002244">COUNT: <a id = "clicks">0</a></p>
</h1>
<button id = "btn_plus" type = "button" onClick = "clickplus()">+1</button>
<button id = "btn_less" type = "button" onClick = "clickless()">-1</button>
</center>
</body>
Может ли кто-нибудь помочь? id="clicks" окрашивает красный цвет, если он отрицательный, и зеленый цвет, если положительный, а также отображает положительный/отрицательный текст на основе этого.
Обратите внимание, что центральный тег устарел. Вы можете узнать о гибкости отображения и о том, как ее использовать, например, для центрирования элементов.
«[Цвет] красный, если отрицательный, и зеленый, если положительный» — а как насчет нуля?
Используйте document.getElementById("clicks").style.color = color;
<body style = "background-color:#F0F0F0">
<center></br></br></br><h1><p style = "color:#002244">CONTAGEM: <a id = "clicks">0</a></p></h1>
<button id = "btn_plus" type = "button" onClick = "clickplus()">+1</button>
<button id = "btn_less" type = "button" onClick = "clickless()">-1</button>
</center>
</body>
<script>
var clicks = 0;
function clickplus() {
clicks += 1;
let color = "black";
let appendText = "";
if (clicks<0){
color = "red";
appendText = "negative";
}else if (clicks>0){
color = "green";
appendText = "positive";
}
document.getElementById("clicks").innerHTML = clicks + " " + appendText;
document.getElementById("clicks").style.color = color;
}
var clicks = 0;
function clickless() {
clicks -= 1;
let color = "black";
let appendText = "";
if (clicks<0){
color = "red";
appendText = "negative";
}else if (clicks>0){
color = "green";
appendText = "positive";
}
document.getElementById("clicks").innerHTML = clicks + " " + appendText;
document.getElementById("clicks").style.color = color;
}
</script>
<style>
#btn_plus{
background-color: #04AA6D; /* Green */
border: none;
color: white;
padding: 15px 32px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;}
#btn_less{
background-color: red; /* Green */
border: none;
color: white;
padding: 15px 32px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;}
</style>
способ повторяющегося кода
Вот современный скрипт, использующий delegation
eventListener
и правильный CSS (center
очень устарел)
Также я поменял кнопки местами, поскольку люди обычно видят отрицательные значения слева от 0.
const container = document.getElementById('centerDiv');
const clickCounter = document.getElementById('clicks');
const posNeg = document.getElementById('posneg');
let clicks = 0;
const clickIt = (e) => {
let tgt = e.target.closest('button.btn');
if (!tgt) return; // not one of the buttons
let increment = tgt.id === 'btn_plus' ? 1 : -1;
clicks += increment;
clickCounter.textContent = clicks;
posNeg.classList.toggle('neg', clicks < 0);
posNeg.classList.toggle('pos', clicks > 0);
};
container.addEventListener('click', clickIt);
body {
background-color: #F0F0F0
}
#centerDiv {
max-width: fit-content;
margin-left: auto;
margin-right: auto;
text-align: center;
}
.btn {
border: none;
color: white;
padding: 15px 32px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
}
#btn_plus {
background-color: #04AA6D;
/* Green */
}
#btn_less {
background-color: red;
}
.pos::after {
color: #04AA6D;
content: 'Positive'
}
.neg::after {
color: red;
content: 'Negative'
}
<div id = "centerDiv">
<h1>
<p id = "counter" style = "color:#002244">COUNT: <a id = "clicks">0</a> <span id = "posneg"></span></p>
</h1>
<button id = "btn_less" class = "btn" type = "button">-1</button>
<button id = "btn_plus" class = "btn" type = "button">+1</button>
</div>
Просто создайте класс CSS, например .negative
, который содержит color: red
. Затем вы можете использовать element.classList.toggle()
, чтобы добавить или удалить класс в зависимости от того, истинно или ложно утверждение. Текст positive
и негативcan be added as pseu-element through CSS using
::afterand
content`:
let count = 0;
const BUTTONS = document.querySelectorAll('button');
BUTTONS.forEach(button => {
button.addEventListener('click', function() {
switch (this.id) {
case 'btn_plus':
count++;
break;
case 'btn_less':
count--;
break;
}
clicks.value = count;
clicks.classList.toggle('negative', (count < 0));
})
})
body {
background-color: #FOFOFO;
margin-top: 3rem;
}
div{
color: #002244;
font-size: 2em;
font-weight: 900;
output {
color: green;
&.negative {
color: red;
&::after {
content: ' negative';
}
}
&::after {
content: ' positive';
}
}
}
#btn_plus {
background-color: #04AA6D;
/* Green */
border: none;
color: white;
padding: 15px 32px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
}
#btn_less {
background-color: red;
/* Green */
border: none;
color: white;
padding: 15px 32px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
}
<body style = "background-color:#F0F0F0">
<div>COUNT: <output id = "clicks" role = "spinbutton">0</output></div>
<button id = "btn_plus" type = "button">+1</button>
<button id = "btn_less" type = "button">-1</button>
</body>
Stack Overflow — это не служба написания кода, а помощь людям с конкретными проблемами кода. Сначала попробуйте найти решение самостоятельно, а затем, если вы застряли, обратитесь за помощью. Я могу заверить вас, что быстрый поиск в Google поможет вам очень быстро выполнить то, что вы пытаетесь сделать.