单击时更改文本框边框

时间:2011-10-09 08:03:26

标签: javascript html css textbox

我正在创建一个网站,并希望文本框的边框颜色在悬停时以及单击时更改。

我搜索过并找到一些人展示了如何操作的代码。我试图从我的LAMP服务器运行它(不知道嵌入式JS是否可以在Lamp服务器上运行)虽然它没有用。代码是javascript,我真的不知道,所以我无法理解出了什么问题。

这是代码:     

onload=function(){
    var inp=document.getElementsByTagName('input'), i=0, t ;
    while(t==inp[i++]){
        if(t.type=='text'){
            t.onclick=function(){this.style.border='1px solid red'}
        }
    }
}

</script>

有没有办法用CSS / html做我想要的东西,还是我还需要学习JavaScript?

如果不太难解释怎么做或给我看一些示例代码?

干杯 - 科恩。

3 个答案:

答案 0 :(得分:3)

是的,这可以使用CSS伪类

来完成

以下是一个例子:

<style>
  .fancyText:hover{border:1px solid red;}
  .fancyText:focus{border:1px solid red;}
</style>
<input type='text' class='fancyText' />

答案 1 :(得分:0)

@Aaron是对的,你可以访问w3school进行css学习,

如果你想使用java脚本,你只需要函数onFocus,onBlur并通过id访问文本框

function change()
    {
        var a = document.getElementById('fansy');
        a.style.border = '1px solid red';
    }

答案 2 :(得分:0)

为什么不使用jQuery来简化它?

$(document).ready(function(){
    $('input').each(function(){
       if($(this).attr('type')=='text')
           {
               $(this).focus(function(){
                   $(this).css({'border':'1px solid red'}); 
               });
               $(this).blur(function(){
                   $(this).css({'border':'1px solid green'});
               });
           }
    });
});

然后您还可以获得多浏览器支持.... 别忘了<script src="[the_path_to_jquery_file]" type="text/javascript"></script> 包含jquery文件。

如果替换此

$('input').each(function(){
       if($(this).attr('type')=='text')
           {
               $(this).focus(function(){
                   $(this).css({'border':'1px solid red'}); 
               });
               $(this).blur(function(){
                   $(this).css({'border':'1px solid green'});
               });
           }
    });

用这个

$('input[type="text"]').each(function(){
          $(this).focus(function(){
                   $(this).css({'border':'1px solid red'}); 
               });
               $(this).blur(function(){
                   $(this).css({'border':'1px solid green'});
               });
    });

您将使用attr自动获取输入。 type = text。 Here is more fact about jQuery attr selecting