使用querySelector改变颜色

Change color using querySelector

本文关键字:变颜色 改变 querySelector 使用      更新时间:2023-09-26

我正在使用一本书学习Javascript教程。练习是用document.querySelector改变<input type="search">的背景颜色。当我尝试在搜索框中搜索没有文本的东西时,<input>的背景变为红色。我用onsubmit和一些条件。但是在接下来的部分,它必须使用onfocus返回到白色背景,我没有得到。

我尝试的代码是

document.querySelector('#form-busca').onsubmit = function() {
    if (document.querySelector('#q').value == '') {
        document.querySelector('#q').style.background = 'red';
        return false;
    }
}
document.querySelector('#form-busca').onfocus = function() {
    document.querySelector('#q').style.background = 'white';
}

有人能帮帮我吗?非常感谢!

马上就明白了。

改变:

document.querySelector('#form-busca').onfocus

:

document.querySelector('#q').onfocus

修改后的代码:

正确的示例:

document.querySelector('#form-busca').onsubmit = function() {
    if (document.querySelector('#q').value == '') {
        document.querySelector('#q').style.background = 'red';
        return false;
    }
}
document.querySelector('#q').onfocus = function() {
    document.querySelector('#q').style.background = 'white';
}

input元素聚焦时,您似乎希望输入的背景颜色更改为白色。

尝试将onfocus选择器更改为:
document.querySelector('#q').onfocus

您希望onfocus处理程序在#q元素上,而不是在#form-busca上;窗体的焦点并不重要,您需要在输入元素获得焦点时清除背景:

document.querySelector('#q').onfocus = function() { ... }

尝试以下代码:

// select
var h1 = document.querySelector("h1");
// manipulate
h1.style.color = "red";

这将使h1的颜色变为红色