placeholder效果

时间:2022-05-05 08:48:22
<!DOCTYPE HTML>
<html lang="en-US">
<head>
    <meta charset="UTF-8">
    <title></title>
    <style type="text/css">
        .txt-input {color:#999;}
    </style>
</head>
<body>
    <form action="">
        <input type="text" name="keywords" value='三体' val='三体' class="txt-input" />
        <input type="submit" value="搜索" />
    </form>
    <script type="text/javascript">
        var inputs = document.getElementsByTagName('input');
        var dval = inputs[0].getAttribute('val');
        //给文本框注册focus事件
        inputs[0].onfocus = function(){
            //需要判断文本框中的内容是否是默认的
            //获取自定义属性
            //清除文本框中的内容
            if (this.value == dval) {
                this.value = "";
            }
            this.style.color = "#333";
        }
        //给文本框注册blur事件
        inputs[0].onblur = function(){
            //需要判断文本框中的内容是否为空
            if (this.value == '') {
                this.value = dval;
                this.style.color = "#999";
            }
        }
    </script>
</body>
</html>