文本输入框有内容时显示清除图标

<!doctype html>
<html lang="zh">
<head>
<meta charset="utf-8">
<title>文本输入框有内容时显示清除图标</title>
</head>
<body>
<style type="text/css">
*{margin:0;padding:0;outline:0;font-size:14px;line-height:1;}
.input-box{position:relative;padding:30px 0 0 30px;width:fit-content;}
.input-box .input-text{padding:0 35px 0 10px;width:250px;height:30px;border:1px solid #3c4042;}
.input-box .clear-input{position:absolute;top:36px;right:6px;display:none;width:20px;height:20px;border-radius:50%;background:#3c4042;color:#fff;cursor:pointer;justify-content:center;align-items:center;user-select:none;}

/********** 重要提醒:以下CSS代码是整个功能的核心 **********/
.input-text:valid+.clear-input{display:flex;}
</style>
<div class="input-box">
    <!-- 重要提醒:<input>必须要有required属性,否则不能控制清除图标隐藏。 -->
    <input name="phone" type="text" class="input-text" placeholder="请输入联系电话" autocomplete="off" required>
    <span class="clear-input" data-target="phone">×</span></div>
<script type="text/javascript" src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script type="text/javascript">
$(function() {
    // 点击清除图标时把输入框清空
    $('.clear-input').click(function() {
        var name = $(this).data('target');
        $('input[name="' + name + '"]').val('');
    });
});
</script>
</body>
</html>

Copyright © 2024 码农人生. All Rights Reserved