使用 querySelector 更改颜色
Change color using querySelector
我正在使用一本书学习 Javascript 教程。
练习是使用 document.querySelector
更改 <input type="search">
中的背景颜色。当我尝试搜索搜索框中没有文本的内容时,<input>
的背景变为红色。我使用 onsubmit
和一些条件来做到这一点。但在接下来的部分,它必须 returns 使用 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';
}
有人可以帮助我吗?非常感谢!
听起来您希望输入的背景颜色在 input
元素获得焦点时变为白色。
尝试将 onfocus
选择器更改为:
document.querySelector('#q').onfocus
...
您希望 onfocus
处理程序位于 #q
元素上,而不是 #form-busca
上;表单的焦点无关紧要,您想在输入元素获得焦点时清除背景:
document.querySelector('#q').onfocus = function() { ... }
差不多明白了伙计。
变化:
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';
}
试试下面的代码:
// select
var h1 = document.querySelector("h1");
// manipulate
h1.style.color = "red";
这将使 h1
的颜色变为红色。
我正在使用一本书学习 Javascript 教程。
练习是使用 document.querySelector
更改 <input type="search">
中的背景颜色。当我尝试搜索搜索框中没有文本的内容时,<input>
的背景变为红色。我使用 onsubmit
和一些条件来做到这一点。但在接下来的部分,它必须 returns 使用 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';
}
有人可以帮助我吗?非常感谢!
听起来您希望输入的背景颜色在 input
元素获得焦点时变为白色。
尝试将 onfocus
选择器更改为:
document.querySelector('#q').onfocus
...
您希望 onfocus
处理程序位于 #q
元素上,而不是 #form-busca
上;表单的焦点无关紧要,您想在输入元素获得焦点时清除背景:
document.querySelector('#q').onfocus = function() { ... }
差不多明白了伙计。
变化:
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';
}
试试下面的代码:
// select
var h1 = document.querySelector("h1");
// manipulate
h1.style.color = "red";
这将使 h1
的颜色变为红色。