JavaScript实现文本框和密码框placeholder效果(兼容ie8)

本文介绍了两种前端表单输入提示的方法,包括文本框和密码框的处理。对于文本框,使用JavaScript实现了默认提示文字在聚焦和失去焦点时的变化;对于密码框,通过监听焦点和 blur 事件,实现在用户交互中切换显示和隐藏密码的功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

文本框:

方法一:

<input type="text" id="add-usbkey-authentication-modal-name" class="form-control"
value="长度为3-128的数字和字母" name="addUsbkeyAuthenticationModalName"
onfocus="if(value=='长度为3-128的数字和字母') {value=''}" 
onblur="if (value=='') {value='长度为3-128的数字和字母'}"
/>

方法二: 

<input type="text" name="hotGoods" id="search">
        $(document).ready(function () {
            $("#search").val('请输入您要搜索的内容').css('color', '#ccc');
            replacePlaceholder($("#search"));
        });

        function replacePlaceholder(input) {
            var originalvalue = input.val(); //请输入您要搜索的内容

            // console.log(originalvalue);
            input.focus(function () {
                if ($.trim(input.val()) == originalvalue) {
                    input.css('color', '#333');
                    input.val('');
                }
            });

            input.blur(function () {
                if ($.trim(input.val()) == '') {
                    input.css('color', '#ccc');
                    input.val(originalvalue);
                }
            });
        }

密码框:

<input type="text" value="长度为12-16的数字和字母" id="add-chap-modal-password-show"  class="form-control"/>
<input type="password" id="add-chap-modal-password" style="display: none" name="addChapModalPassword" class="form-control"/>
        $('#add-chap-modal-password-show').focus(function () {
            var text_value = $(this).val();
            if (text_value == this.defaultValue) {
                $('#add-chap-modal-password-show').hide();
                $('#add-chap-modal-password').show().focus();
            }
        });
        
        $('#add-chap-modal-password').blur(function () {
            var text_value = $(this).val();
            if (text_value == "") {
                $('#add-chap-modal-password-show').show();
                $('#add-chap-modal-password').hide();
            }
        });

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值