上节课我们基本完成了游戏的主体,这节课我们来学习如果使用JavaScript去操作CSS样式
● 例如,我们现在想当玩家输入对的数字之后,我们讲背景改为绿色,并且把number的框宽度变大
const secretnumber = Math.trunc(Math.random() * 20) + 1;
let score = 20;
document.querySelector('.number').textContent = secretnumber;
document.querySelector('.check').addEventListener('click', function () {
const guess = Number(document.querySelector('.guess').value);
console.log(guess);
if (!guess) {
document.querySelector('.message').textContent = '⛔No Number';
} else if (guess === secretnumber) {
document.querySelector('.message').textContent = 'Correct Number';
document.querySelector('body').style.backgroundColor = '#60b347';
document.querySelector('.number').style.width = '30rem';
} else if (guess > secretnumber) {
if (score > 1) {
document.querySelector('.message').textContent = 'Too high';
score--;
document.querySelector('.score').textContent = score;
} else {
document.querySelector('.message').textContent = 'You lost the game!';
document.querySelector('.score').textContent = 0;
}
} else if (guess < secretnumber) {
if (score > 1) {
document.querySelector('.message').textContent = 'Too low';
score--;
document.querySelector('.score').textContent = score;
} else {
document.querySelector('.message').textContent = 'You lost the game';
document.querySelector('.score').textContent = 0;
}
}
});
在JavaScript中操作CSS样式时,有几个注意事项需要牢记: