最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Change color using querySelector - Stack Overflow

programmeradmin2浏览0评论

I'm following a Javascript tutorial using a book. The exercise is change the background color in a <input type="search"> using document.querySelector. When I try to search something with no text in the search box, the background from <input> changes to red. I did it using onsubmit and some conditional. But in the next part, it must returns to white bckground using onfocus and I'm not getting.

The code that I tried is

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';
}

Can someone help me? Thanks a lot!

I'm following a Javascript tutorial using a book. The exercise is change the background color in a <input type="search"> using document.querySelector. When I try to search something with no text in the search box, the background from <input> changes to red. I did it using onsubmit and some conditional. But in the next part, it must returns to white bckground using onfocus and I'm not getting.

The code that I tried is

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';
}

Can someone help me? Thanks a lot!

Share Improve this question asked Jun 23, 2016 at 22:44 hugolcoutohugolcouto 871 gold badge2 silver badges7 bronze badges
Add a comment  | 

4 Answers 4

Reset to default 8

almost got it dude.

change:

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

to:

document.querySelector('#q').onfocus

revised code:

correct sample:

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';
}

It sounds like you want the input's background color to change to white when the input element is focused.

Try changing your onfocus selector to:
document.querySelector('#q').onfocus ...

You want the onfocus handler to be on the #q element, not on #form-busca; the form's focus doesn't matter, you want to clear the background when the input element gains focus:

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

Try the following code:

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

This will make the color of h1 red.

发布评论

评论列表(0)

  1. 暂无评论