0

如何修改下面的代码,以便将onblurandonfocus应用于文本框和选择框?现在它只适用于文本框,我似乎无法让它应用于选择框。

<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">

window.onload = 

function fnOnLoad() {
        var t = document.getElementsByTagName('INPUT');

        var i;
        for(i=0;i<t.length;i++)
        {
            //alert(t[i].type)

            if(t[i].type == "text")
            {
                t[i].attachEvent('onfocus', new Function("fnTXTFocus('"+t[i].id+ "')"));
                t[i].attachEvent('onblur', new Function("fnTXTLostFocus('"+t[i].id+ "')"));
            }
        }
    }


function fnTXTFocus(varname) {

        var objTXT = document.getElementById(varname)
        objTXT.style.backgroundColor = "#FFFF80";

    }

    function fnTXTLostFocus(varname)
    {
        var objTXT = document.getElementById(varname)
        objTXT.style.backgroundColor = "#FFFFFF";
    }


</script>


</head>
<body>

<input id="t1" type="text" >
<input id="t2" type="text" >
<input id="t3" type="text" >
<br><br>
<select size="d1" ></select>
<select size="d2" ></select>
<select size="d3" ></select>
<p>When the input field gets focus, 
   a function is triggered which changes the background-color.</p>

</body>
</html>
4

3 回答 3

0

尝试这个:

function fnOnLoad() {
    var inputs = document.getElementsByTagName('INPUT');
    for(var i = 0; i < inputs.length; i++)
    {
        inputs[i].attachEvent('onfocus', function(){ 
             this.style.backgroundColor = "#FFFF80";
        });
        inputs[i].attachEvent('onblur', function(){ 
             this.style.backgroundColor = "#FFFFFF";
        });
    }

    var selects = document.getElementsByTagName('SELECT');
    for(var i = 0; i < selects.length; i++)
    {
        selects[i].attachEvent('onfocus', function(){ 
             this.style.backgroundColor = "#FFFF80";
        });
        selects[i].attachEvent('onblur', function(){ 
             this.style.backgroundColor = "#FFFFFF";
        });
    }
}

window.onload = fnOnLoad;
于 2012-10-16T17:24:09.380 回答
0

因此,您还需要获取所有选择并将事件处理程序附加到它们:

var s = document.getElementsByTagName('SELECT');
于 2012-10-16T17:24:09.770 回答
-1
<script type="text/javascript">

function fnOnLoad() {

    var t = document.getElementsByTagName('INPUT');
    for (var i = 0; i < t.length; i++) {
            t[i].onfocus = function() { this.style.backgroundColor = '#FFFFC4';};
            t[i].onblur = function() { this.style.backgroundColor = '#FFFFFF'; };
    }

    var d = document.getElementsByTagName('SELECT');
    for (var i = 0; i < d.length; i++) {
            d[i].onfocus = function() { this.style.backgroundColor = '#FFFFC4'; };
            d[i].onblur = function() { this.style.backgroundColor = '#FFFFFF'; };
    }

}
</script>
于 2012-10-16T18:50:49.223 回答