1

我试过这段代码,但它不起作用..当我聚焦文本框时它显示错误

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

5 回答 5

4

此任务不需要 JavaScript,只需使用 css(:focus从 IE8 开始支持)

https://developer.mozilla.org/en-US/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; }
于 2013-04-12T15:20:33.320 回答
2

obj.style.background = "#C8C8C8";

于 2013-04-12T15:19:46.353 回答
1

是的,你应该试试这个 javascript 代码来改变这个元素的背景颜色:

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

现在你可以改变你想要的任何颜色

于 2013-04-12T15:34:05.043 回答
1

是什么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。

于 2013-04-12T15:26:46.737 回答
0

尝试用 jQuery 来做。

$('#div').on('focus', function() {
    $(this).css({background:'blue'});
});
于 2013-04-12T15:19:36.327 回答