JavaScript实现输入框与清空按钮联动效果

作者:代码拾荒

时间:2026-10-30

浏览:162

本文介绍了如何使用JavaScript结合jQuery实现输入框与清空按钮的联动效果。通过监听输入框值的变化,动态判断是否显示或隐藏清空按钮,提升用户交互体验。

文章目录

输入框与清空按钮联动实现

以下是实现该功能的关键代码示例:


<!DOCTYPE html><html><head><metacharset="UTF-8"><title>输入框清空按钮</title><scriptsrc="js/jquery1.8.3.min.js"></script><script>/**
* 校验当前输入框的值,如果不为空显示清空按钮
* @param element
*/functioncheckInput(element){var value = $(element).val();
if(value!=null&&''!=value)
$(element).parent().parent().children().children('.button').removeClass('none');
else
$(element).parent().parent().children().children('.button').addClass('none');
}
/**
* 清空输入框内容
* @param element
*/functionclearInput(element){
$(element).parent().parent().children().children('input').val('');
$(element).addClass('none');
}
</script><style>.none{
display: none;
}.height-20{
height:20px;;}.button{
color: red;
font-size:18px;
width:100px;
height:18px;;border:1px solid red;
border-radius:5px;
}</style></head><body><div><div><inputtype="text"placeholder="输入试试看"onkeyup="checkInput(this);" >
</div><divclass="height-20" ></div><div>
<aclass="none button"onclick="clearInput(this);" >clear input</a></div></div></body>
</html>
').addClass('pre-numbering').hide(); $(this).addClass('has-numbering').parent().append($numbering); for (i = 1; i <= lines; i++)
{ $numbering.append($('
').text(i)); }; $numbering.fadeIn(1700); }); });

上述内容介绍了利用JavaScript实现输入框与清空按钮联动的具体方法,希望能对大家有所帮助。如有任何疑问,欢迎留言,小编会及时回复。在此感谢大家对本站的支持!

实用工具推荐

电子包浆

绿化、压缩、噪点和虚拟水印,自由调节做旧程度。

使用 ›
图片压缩

选择画质和输出格式,预览压缩前后的大小。

使用 ›
相关文章