我想要一个漂亮的小图标,点击后会清除<INPUT>框中的文字。
这是为了节省空间,而不是在输入框外部有明确的链接。
我的CSS很差,.这是iPhone外观的截图。
发布于 2018-04-02 14:30:52
只能使用JavaScript来使该按钮工作。这是一个SSCCE,你可以尝试一下:
<!DOCTYPE html>
<html lang="en">
<head>
<title>SO question 2803532</title>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
$(document).ready(function() {
$('input.deletable').wrap('<span class="deleteicon" />').after($('<span/>').click(function() {
$(this).prev('input').val('').trigger('change').focus();
}));
});
</script>
<style>
span.deleteicon {
position: relative;
}
span.deleteicon span {
position: absolute;
display: block;
top: 5px;
right: 0px;
width: 16px;
height: 16px;
background: url('http://cdn.sstatic.net/stackoverflow/img/sprites.png?v=4') 0 -690px;
cursor: pointer;
}
span.deleteicon input {
padding-right: 16px;
box-sizing: border-box;
}
</style>
</head>
<body>
<input type="text" class="deletable">
</body>
</html>
jQuery是没有必要的,它很好地将渐进增强所需的逻辑与源代码分开,当然也可以继续使用纯 HTML / CSS / JS:
<!DOCTYPE html>
<html lang="en">
<head>
<title>SO question 2803532, with "plain" HTML/CSS/JS</title>
<style>
span.deleteicon {
position: relative;
}
span.deleteicon span {
position: absolute;
display: block;
top: 5px;
right: 0px;
width: 16px;
height: 16px;
background: url('http://cdn.sstatic.net/stackoverflow/img/sprites.png?v=4') 0 -690px;
cursor: pointer;
}
span.deleteicon input {
padding-right: 16px;
box-sizing: border-box;
}
</style>
</head>
<body>
<span class="deleteicon">
<input type="text">
<span onclick="var input = this.previousSibling; input.value = ''; input.focus();"></span>
</span>
</body>
</html>
只能得到丑的HTML(和非交叉浏览器兼容的JS;))。
请注意,当用户界面的使用感受不是最关心的,但功能是,然后才是使用,<input type="search">
而不是<input type="text">
。它会在支持HTML5的浏览器上显示(浏览器特定的)清除按钮。
发布于 2018-04-02 15:32:24
现在使用HTML5,这非常简单:
<input type="search" placeholder="Search..."/>
大多数现代浏览器默认会自动在字段中显示可用的清除按钮。
(如果使用Bootstrap,必须在css文件中添加一个覆盖来显示它)
input[type=search]::-webkit-search-cancel-button {
-webkit-appearance: searchfield-cancel-button;
}
Safari / WebKit浏览器还可以在使用时提供额外的功能type="search"
,例如results=5
和autosave="..."
,但它们也覆盖很多样式(例如高度,边框)。为了防止这些覆盖,同时仍然保留像X按钮一样的功能,可以将其添加到css中:
input[type=search] {
-webkit-appearance: none;
}
https://stackoverflow.com/questions/-100007910
复制相似问题