我希望当我点击我的输入以更改字段的背景颜色时。我想通过调用函数来实现。我究竟做错了什么 ?谢谢!
<input type="text" onFocus="makefieldred();" onBlur="makefieldwhite();" >
<script>
function makefieldred() {
this.style.backgroundcolor='red' ;
}
function makefieldwhite() {
this.style.backgroundcolor='white' ;
}
</script>
答案 0 :(得分:3)
this
不是元素,因为你将它们连接起来的方式。此外,媒体资源名称为backgroundColor
(资本C
),而不是backgroundcolor
:
如果您想使用onXyz
属性机制,最简单的方法是将元素传递给函数:
<input type="text" onFocus="makefieldred(this);" onBlur="makefieldwhite(this);" >
<script>
function makefieldred(elm) {
elm.style.backgroundColor='red' ;
}
function makefieldwhite(elm) {
elm.style.backgroundColor='white' ;
}
</script>
或者,使用现代技术设置事件处理程序:
<input type="text" id="the Input">
<script>
(function() {
var input = document.getElementById("theInput");
input.addEventListener("focus", makefieldred, false);
input.addEventListener("blur", makefieldwhite, false);
function makefieldred() {
this.style.backgroundColor='red' ;
}
function makefieldwhite() {
this.style.backgroundColor='white' ;
}
</script>
如果您必须支持IE8,如果您在attachEvent
上看不到addEventListener
,则需要使用input
。要处理浏览器不兼容性,您可以使用函数(taken from my other answer here):
var hookEvent = (function() {
var div;
// The function we use on standard-compliant browsers
function standardHookEvent(element, eventName, handler) {
element.addEventListener(eventName, handler, false);
return element;
}
// The function we use on browsers with the previous Microsoft-specific mechanism
function oldIEHookEvent(element, eventName, handler) {
element.attachEvent("on" + eventName, function(e) {
e = e || window.event;
e.preventDefault = oldIEPreventDefault;
e.stopPropagation = oldIEStopPropagation;
handler.call(element, e);
});
return element;
}
// Polyfill for preventDefault on old IE
function oldIEPreventDefault() {
this.returnValue = false;
}
// Polyfill for stopPropagation on old IE
function oldIEStopPropagation() {
this.cancelBubble = true;
}
// Return the appropriate function; we don't rely on document.body
// here just in case someone wants to use this within the head
div = document.createElement('div');
if (div.addEventListener) {
div = undefined;
return standardHookEvent;
}
if (div.attachEvent) {
div = undefined;
return oldIEHookEvent;
}
throw "Neither modern event mechanism (addEventListener nor attachEvent) is supported by this browser.";
})();
然后:
<script>
(function() {
var input = document.getElementById("theInput");
hookEvent(input, "focus", makefieldred);
hookEvent(input, "blur", makefieldwhite);
function makefieldred() {
this.style.backgroundColor='red' ;
}
function makefieldwhite() {
this.style.backgroundColor='white' ;
}
</script>