Javascript 输入文本内的清除图标
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6258521/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Clear icon inside input text
提问by Giovanni Di Milia
Is there a quick way to create an input text element with an icon on the right to clear the input element itself (like the google search box)?
有没有一种快速的方法来创建一个带有右侧图标的输入文本元素来清除输入元素本身(如谷歌搜索框)?
I looked around but I only found how to put an icon as background of the input element. Is there a jQuery plugin or something else?
我环顾四周,但我只找到了如何将图标作为输入元素的背景。是否有 jQuery 插件或其他东西?
I want the icon inside the input text element, something like:
我想要输入文本元素内的图标,例如:
--------------------------------------------------
| X|
--------------------------------------------------
回答by Roko C. Buljan
Add a type="search"
to your input
The support is pretty decent but will not work in IE<10
type="search"
在您的输入中添加一个
支持相当不错,但在 IE<10 中不起作用
<input type="search">
Clearable input for old browsers
旧浏览器的可清除输入
If you need IE9 supporthere are some workarounds
如果您需要IE9 支持,这里有一些解决方法
Using a standard <input type="text">
and some HTML elements:
使用标准<input type="text">
和一些 HTML 元素:
/**
* Clearable text inputs
*/
$(".clearable").each(function() {
var $inp = $(this).find("input:text"),
$cle = $(this).find(".clearable__clear");
$inp.on("input", function(){
$cle.toggle(!!this.value);
});
$cle.on("touchstart click", function(e) {
e.preventDefault();
$inp.val("").trigger("input");
});
});
/* Clearable text inputs */
.clearable{
position: relative;
display: inline-block;
}
.clearable input[type=text]{
padding-right: 24px;
width: 100%;
box-sizing: border-box;
}
.clearable__clear{
display: none;
position: absolute;
right:0; top:0;
padding: 0 8px;
font-style: normal;
font-size: 1.2em;
user-select: none;
cursor: pointer;
}
.clearable input::-ms-clear { /* Remove IE default X */
display: none;
}
<span class="clearable">
<input type="text" name="" value="" placeholder="">
<i class="clearable__clear">×</i>
</span>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Using only a <input class="clearable" type="text">
(No additional elements)
仅使用一个<input class="clearable" type="text">
(无附加元素)
set a class="clearable"
and play with it's background image:
设置 aclass="clearable"
并使用它的背景图像:
/**
* Clearable text inputs
*/
function tog(v){return v?'addClass':'removeClass';}
$(document).on('input', '.clearable', function(){
$(this)[tog(this.value)]('x');
}).on('mousemove', '.x', function( e ){
$(this)[tog(this.offsetWidth-18 < e.clientX-this.getBoundingClientRect().left)]('onX');
}).on('touchstart click', '.onX', function( ev ){
ev.preventDefault();
$(this).removeClass('x onX').val('').change();
});
// $('.clearable').trigger("input");
// Uncomment the line above if you pre-fill values from LS or server
/* Clearable text inputs */
.clearable{
background: #fff url(http://i.stack.imgur.com/mJotv.gif) no-repeat right -10px center;
border: 1px solid #999;
padding: 3px 18px 3px 4px; /* Use the same right padding (18) in jQ! */
border-radius: 3px;
transition: background 0.4s;
}
.clearable.x { background-position: right 5px center; } /* (jQ) Show icon */
.clearable.onX{ cursor: pointer; } /* (jQ) hover cursor style */
.clearable::-ms-clear {display: none; width:0; height:0;} /* Remove IE default X */
<input class="clearable" type="text" name="" value="" placeholder="" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
The trick is to set some right padding (I used 18px) to the input
and push the background-image right, out of sight (I used right -10px center
).
That 18px padding will prevent the text hide underneath the icon (while visible).
jQ will add the class x
(if input
has value) showing the clear icon.
Now all we need is to target with jQ the inputs with class x
and detect on mousemove
if the mouse is inside that 18px "x" area; if inside, add the class onX
.
Clicking the onX
class removes all classes, resets the input value and hides the icon.
诀窍是为 设置一些正确的填充(我使用 18px)input
并将背景图像推到视线之外(我使用right -10px center
)。
18px 填充将防止文本隐藏在图标下方(可见时)。
jQ 将添加显示清除图标的类x
(如果input
有值)。
现在我们只需要用 jQ 将输入作为目标,x
然后检测mousemove
鼠标是否在 18px 的“x”区域内;如果在里面,添加 class onX
。
单击onX
类将删除所有类、重置输入值并隐藏图标。
7x7px gif:
7x7px gif:
Base64 string:
Base64 字符串:
data:image/gif;base64,R0lGODlhBwAHAIAAAP///5KSkiH5BAAAAAAALAAAAAAHAAcAAAIMTICmsGrIXnLxuDMLADs=
回答by David says reinstate Monica
Could I suggest, if you're okay with this being limited to html 5 compliant browsers, simply using:
我可以建议,如果你同意这仅限于 html 5 兼容的浏览器,只需使用:
<input type="search" />
Admittedly, in Chromium (Ubuntu 11.04), this does require there to be text inside the input
element beforethe clear-text image/functionality will appear.
诚然,在 Chromium (Ubuntu 11.04) 中,这确实需要在input
元素内部有文本,然后才能出现明文图像/功能。
Reference:
参考:
回答by KOGI
You could use a reset button styled with an image...
您可以使用带有图像样式的重置按钮...
<form action="" method="get">
<input type="text" name="search" required="required" placeholder="type here" />
<input type="reset" value="" alt="clear" />
</form>
<style>
input[type="text"]
{
height: 38px;
font-size: 15pt;
}
input[type="text"]:invalid + input[type="reset"]{
display: none;
}
input[type="reset"]
{
background-image: url( http://png-5.findicons.com/files/icons/1150/tango/32/edit_clear.png );
background-position: center center;
background-repeat: no-repeat;
height: 38px;
width: 38px;
border: none;
background-color: transparent;
cursor: pointer;
position: relative;
top: -9px;
left: -44px;
}
</style>
See it in action here: http://jsbin.com/uloli3/63
在这里查看它的实际效果:http: //jsbin.com/uloli3/63
回答by Shidhin Cr
I've created a clearable textbox in just CSS. It requires no javascript code to make it work
我只用 CSS 创建了一个可清除的文本框。它不需要 javascript 代码就可以工作
below is the demo link
下面是演示链接
回答by Josh Crozier
According to MDN, <input type="search" />
is currently supported in all modern browsers:
根据 MDN,<input type="search" />
目前所有现代浏览器都支持:
<input type="search" value="Clear this." />
However, if you want different behavior that is consistent across browsers here are some light-weight alternatives that only require JavaScript:
但是,如果您希望跨浏览器保持一致的不同行为,这里有一些仅需要 JavaScript 的轻量级替代方案:
Option 1 - Always display the 'x': (example here)
选项 1 - 始终显示“x”:(此处示例)
Array.prototype.forEach.call(document.querySelectorAll('.clearable-input>[data-clear-input]'), function(el) {
el.addEventListener('click', function(e) {
e.target.previousElementSibling.value = '';
});
});
.clearable-input {
position: relative;
display: inline-block;
}
.clearable-input > input {
padding-right: 1.4em;
}
.clearable-input > [data-clear-input] {
position: absolute;
top: 0;
right: 0;
font-weight: bold;
font-size: 1.4em;
padding: 0 0.2em;
line-height: 1em;
cursor: pointer;
}
.clearable-input > input::-ms-clear {
display: none;
}
<p>Always display the 'x':</p>
<div class="clearable-input">
<input type="text" />
<span data-clear-input>×</span>
</div>
<div class="clearable-input">
<input type="text" value="Clear this." />
<span data-clear-input>×</span>
</div>
Option 2 - Only display the 'x' when hovering over the field: (example here)
选项 2 - 仅在将鼠标悬停在字段上时显示“x”:(此处示例)
Array.prototype.forEach.call(document.querySelectorAll('.clearable-input>[data-clear-input]'), function(el) {
el.addEventListener('click', function(e) {
e.target.previousElementSibling.value = '';
});
});
.clearable-input {
position: relative;
display: inline-block;
}
.clearable-input > input {
padding-right: 1.4em;
}
.clearable-input:hover > [data-clear-input] {
display: block;
}
.clearable-input > [data-clear-input] {
display: none;
position: absolute;
top: 0;
right: 0;
font-weight: bold;
font-size: 1.4em;
padding: 0 0.2em;
line-height: 1em;
cursor: pointer;
}
.clearable-input > input::-ms-clear {
display: none;
}
<p>Only display the 'x' when hovering over the field:</p>
<div class="clearable-input">
<input type="text" />
<span data-clear-input>×</span>
</div>
<div class="clearable-input">
<input type="text" value="Clear this." />
<span data-clear-input>×</span>
</div>
Option 3 - Only display the 'x' if the input
element has a value: (example here)
选项 3 - 如果input
元素具有值,则仅显示“x” :(此处示例)
Array.prototype.forEach.call(document.querySelectorAll('.clearable-input'), function(el) {
var input = el.querySelector('input');
conditionallyHideClearIcon();
input.addEventListener('input', conditionallyHideClearIcon);
el.querySelector('[data-clear-input]').addEventListener('click', function(e) {
input.value = '';
conditionallyHideClearIcon();
});
function conditionallyHideClearIcon(e) {
var target = (e && e.target) || input;
target.nextElementSibling.style.display = target.value ? 'block' : 'none';
}
});
.clearable-input {
position: relative;
display: inline-block;
}
.clearable-input > input {
padding-right: 1.4em;
}
.clearable-input >[data-clear-input] {
display: none;
position: absolute;
top: 0;
right: 0;
font-weight: bold;
font-size: 1.4em;
padding: 0 0.2em;
line-height: 1em;
cursor: pointer;
}
.clearable-input > input::-ms-clear {
display: none;
}
<p>Only display the 'x' if the `input` element has a value:</p>
<div class="clearable-input">
<input type="text" />
<span data-clear-input>×</span>
</div>
<div class="clearable-input">
<input type="text" value="Clear this." />
<span data-clear-input>×</span>
</div>
回答by wldaunfr
Since none of the solutions flying around really met our requirements, we came up with a simple jQuery plugin called jQuery-ClearSearch-
由于周围的解决方案都没有真正满足我们的要求,我们想出了一个简单的 jQuery 插件,称为jQuery-ClearSearch-
using it is as easy as:
使用它就像:
<input class="clearable" type="text" placeholder="search">
<script type="text/javascript">
$('.clearable').clearSearch();
</script>
? Example: http://jsfiddle.net/wldaunfr/FERw3/
回答by Jonathan Lonowski
If you want it like Google, then you should know that the "X" isn't actually inside the <input>
-- they're next to each other with the outer container styled to appear like the text box.
如果您像 Google 一样想要它,那么您应该知道“X”实际上不在内部<input>
——它们彼此相邻,外部容器的样式看起来像文本框。
HTML:
HTML:
<form>
<span class="x-input">
<input type="text" class="x-input-text" />
<input type="reset" />
</span>
</form>
CSS:
CSS:
.x-input {
border: 1px solid #ccc;
}
.x-input input.x-input-text {
border: 0;
outline: 0;
}
Example: http://jsfiddle.net/VTvNX/
回答by Jaspero
EDIT:I found this link. Hope it helps. http://viralpatel.net/blogs/2011/02/clearable-textbox-jquery.html
编辑:我找到了这个链接。希望能帮助到你。http://viralpatel.net/blogs/2011/02/clearable-textbox-jquery.html
You have mentioned you want it on the right of the input text. So, the best way would be to create an image next to the input box. If you are looking something inside the box, you can use background image but you may not be able to write a script to clear the box.
您已经提到您希望它位于输入文本的右侧。因此,最好的方法是在输入框旁边创建一个图像。如果您正在查看框中的内容,则可以使用背景图像,但您可能无法编写脚本来清除框。
So, insert and image and write a JavaScript code to clear the textbox.
因此,插入图像并编写 JavaScript 代码来清除文本框。
回答by Toki
Something like this??Jsfiddle Demo
这种东西??Jsfiddle 演示
<!DOCTYPE html>
<html>
<head>
<title></title>
<style type="text/css">
.searchinput{
display:inline-block;vertical-align: bottom;
width:30%;padding: 5px;padding-right:27px;border:1px solid #ccc;
outline: none;
}
.clearspace{width: 20px;display: inline-block;margin-left:-25px;
}
.clear {
width: 20px;
transition: max-width 0.3s;overflow: hidden;float: right;
display: block;max-width: 0px;
}
.show {
cursor: pointer;width: 20px;max-width:20px;
}
form{white-space: nowrap;}
</style>
</head>
<body>
<form>
<input type="text" class="searchinput">
</form>
<script src="jquery-1.11.3.min.js" type="text/javascript"></script> <script>
$(document).ready(function() {
$("input.searchinput").after('<span class="clearspace"><i class="clear" title="clear">✗</i></span>');
$("input.searchinput").on('keyup input',function(){
if ($(this).val()) {$(".clear").addClass("show");} else {$(".clear").removeClass("show");}
});
$('.clear').click(function(){
$('input.searchinput').val('').focus();
$(".clear").removeClass("show");
});
});
</script>
</body>
</html>
回答by Juboraj Sarker
<form action="" method="get">
<input type="text" name="search" required="required" placeholder="type here" />
<input type="reset" value="" alt="clear" />
</form>
<style>
input[type="text"]
{
height: 38px;
font-size: 15pt;
}
input[type="text"]:invalid + input[type="reset"]{
display: none;
}
input[type="reset"]
{
background-image: url( http://png-5.findicons.com/files/icons/1150/tango/32/edit_clear.png );
background-position: center center;
background-repeat: no-repeat;
height: 38px;
width: 38px;
border: none;
background-color: transparent;
cursor: pointer;
position: relative;
top: -9px;
left: -44px;
}
</style>