input获取焦点时移除placeholder,失去焦点重新获得placeholder内容

获取焦点时移除placeholder,失去焦点重新获得placeholder内容图片描述

阅读 12.4k
5 个回答

有个很简单的方法

input:focus::-webkit-input-placeholder{
color: transparent;
}
/* transparent是全透明黑色(black)的速记法,即一个类似rgba(0,0,0,0)这样的值 */
var arrplaceholder = [1,1,1,1];
$("input").focus(function(){
    if(!!!$(this).prop("readonly")){
        $(this).prop("placeholder", "")
    }
});
$("input").blur(function(){
    $(this).prop("placeholder", arrplaceholder[$(this).index()])
});
    <body>
        <input id="test" placeholder="请输入"></input>
    </body>
    <script type="text/javascript">
        test.addEventListener('focus',function(){
            test.removeAttribute('placeholder')
        });
        test.addEventListener('blur',function(){
            test.setAttribute('placeholder','请输入')
        });
    </script>

原生JS...

我很早很早之前写了一个方法:

(function($) {  
    $.fn.extend({  
        placeholder: function() {  
            if ("placeholder" in document.createElement("input")) {  
                return this //如果原生支持placeholder属性,则返回对象本身  
            } else {  
                return this.each(function() {  
                    var _this = $(this);  
                    _this.val(_this.attr("placeholder")).focus(function() {  
                        if (_this.val() === _this.attr("placeholder")) {  
                            _this.val("")  
                        }  
                    }).blur(function() {  
                        if (_this.val().length === 0) {  
                            _this.val(_this.attr("placeholder"))  
                        }  
                    })  
                })  
            }  
        }  
    })  
})(jQuery); 

推荐这篇文章看看: 这里

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题