繁体   English   中英

对焦时如何更改文本框的背景颜色?

[英]How do i change Background color of textbox when onfocus?

我尝试了这段代码,但是它不起作用..当我将焦点对准文本框时,它显示错误

   function ChangeBgColor(obj, evt) 
    { 
            if(evt.type=="focus") 
                style.background ="lightgrey";
            else if(evt.type=="blur") 
            {
               style.background="white";
            }          
    }

不需要JavaScript,只需使用CSS(自IE8起就支持:focus

https://developer.mozilla.org/zh-CN/docs/CSS/:focus

input { background: lightgray; }
input:focus { background: white; }

只有在< IE8上也绝对需要这种效果时,才可以使用JS(适当地包装在条件注释中),但是即使在这种情况下,也建议不要将样式与逻辑保持一致:例如

function ChangeBgColor(obj, evt) { 
    obj.className = (evt.type === "focus") ? "focus" : "";
}

并使用这种风格

 input { background: lightgray; }

 input:focus, 
 input.focus { background: white; }

obj.style.background = "#C8C8C8";

什么是style 您尚未在上面的代码中的任何地方定义它:

function ChangeBgColor(obj, evt) 
{ 
    if(evt.type=="focus") 
        style.background ="lightgrey";  //<--what is style?
    else if(evt.type=="blur") 
    {
        style.background="white";
    }          
}

我猜你想要类似的东西

obj.style.background ="lightgrey";

在上面的代码中,简化了

function ChangeBgColor(obj, evt) 
{ 
    obj.style.background = (evt.type=="focus") ? "lightgrey" : "white";
}

最好的答案是使用纯CSS。

是的,您应该尝试使用以下JavaScript代码更改此元素的背景色:

  var obj = document.getElementById("yourId"); obj.onfocus = function() { obj.style.backgroundColor = 'red'; } 

现在您可以更改所需的任何颜色

尝试使用jQuery。

$('#div').on('focus', function() {
    $(this).css({background:'blue'});
});

暂无
暂无

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

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