以下代码旨在更改一个字段的颜色:
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>
<body>
<form></form>
<form>
<input name="thisone" />
</form>
<script language="javascript">
var bkColor = "red";
function getEvent(e){
if(window.event != null) {
return event;
}
return e;
}
function setBKColor(e){
e = getEvent(e);
var src = e.srcElement || e.target;
window.status="t";
if(src != null) {
src.style.bkColor = src.style.backgroundColor;
src.style.backgroundColor = bkColor;
}
}
function reSetBKColor(e){
e = getEvent(e);
var src = e.srcElement || e.target;
if(src != null) {
src.style.backgroundColor = src.style.bkColor;
}
}
function attachEvent(name,element,callBack) {
if (element.addEventListener) {
element.addEventListener(name, callBack,false);
} else if (element.attachEvent) {
element.attachEvent('on' + name, callBack);
}
}
function setListner(eve,func) {
var ele = document.forms[0].elements;
for(var i = 0; i <ele.length;i++) {
element = ele[i];
if (element.name) {
switch (element.name) {
case 'thisone':
attachEvent(eve,element,func);
}
}
}
}
setListner("focus",setBKColor);
setListner("blur",reSetBKColor);
</script>
但是,当在更改颜色的字段之前有另一个表单时,代码将停止工作。所以目前 HTML 代码可能看起来像这样,以匹配不便之处:
<name="thisone">
<form></form>
<form></form>
现在这段代码有效。
但是如何使 JS 部分独立于<form>
,并且只依赖于<Name>
文本字段呢?