下拉的阴影颜色和焦点/ onblur上的选择

时间:2012-10-16 17:19:58

标签: javascript html drop-down-menu onfocus dropdownbox

如何修改以下代码,以便将onbluronfocus应用于文本框并选择框?现在它只适用于文本框,我似乎无法将其应用于选择框。

<!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>

3 个答案:

答案 0 :(得分: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;

答案 1 :(得分:0)

所以你需要做的就是获取所有选择并将事件处理程序附加到它们:

var s = document.getElementsByTagName('SELECT');

答案 2 :(得分:-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>