2013-04-12 83 views

回答

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。

+0

其工作很棒 –

0

尝试用jQuery做。

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

的OP可能不想要一个jQuery的答案。 – Mooseman

+0

是的Mooseman im仅在JavaScript中找到答案 –

2

obj.style.background = "#C8C8C8";

4

JavaScript是没有必要为这个任务,只需使用CSS(:focus因为IE8支持)

https://developer.mozilla.org/en-US/docs/CSS/:focus

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

只有当这个效果是对于< IE8 t也绝对需要可以使用hen JS(正确包装在条件注释中),但即使在这种情况下,也建议避免使用逻辑风格:例如

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

,并使用这种风格

input { background: lightgray; } 

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

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

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

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

相关问题