简体   繁体   English

Javascript-更改输入背景

[英]Javascript - Change input background

I have a function to change the background of a search box to red when a user tries to submit it but it's empty and then change it back to 'none' when user clicks on it, like this: 我有一个功能,当用户尝试提交搜索框时将其背景更改为红色,但背景为空,然后在用户单击它时将其更改回“无”,如下所示:

HTML: HTML:

<form action="http://www.google.com/search" id="search-box">
        <input type="search" name="q" id="q" />
        <input type="image" src="img/search.png" />
</form>

Javascript: Javascript:

document.querySelector('#search-box').onsubmit = function () {
    if (document.querySelector('#q').value == '') {
        document.querySelector('#q').style.background = 'red';
        return false;
    }
}

document.querySelector('#q').onclick = function () {
    if (document.querySelector('#q').style.background == 'red') {
        document.querySelector('#q').style.background = '';
        return false;
    }
}

It works fine on chrome, but it doesn't works on firefox... any ideas why? 它在chrome上可以正常工作,但是在Firefox上却不能工作...为什么有任何想法?

When you document.querySelector('#q').style.background it sets the element's background attribute to background: none repeat scroll 0% 0% #F00; 当您document.querySelector('#q').style.background它将元素的background属性设置为background: none repeat scroll 0% 0% #F00;

To achieve what you want, set the ...style.backgroundColor instead, as such 要实现您想要的,请设置...style.backgroundColor ,如下所示

document.querySelector('#search-box').onsubmit = function () {
    if (document.querySelector('#q').value == '') {
        document.querySelector('#q').style.backgroundColor = 'red';
        return false;
    }
}

document.querySelector('#q').onclick = function () {
    if (document.querySelector('#q').style.backgroundColor == 'red') {
        document.querySelector('#q').style.backgroundColor = '';
        return false;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM