有没有一种快速的方法来创建一个输入文本元素,在右边有一个图标,以清除输入元素本身(如谷歌搜索框)?

我环顾四周,但我只发现如何把一个图标作为输入元素的背景。有jQuery插件或其他什么?

我想在输入文本元素内的图标,类似于:

--------------------------------------------------
|                                               X|
--------------------------------------------------

你可以使用一个带有图像样式的重置按钮…

<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>

在这里查看它的实际操作:http://jsbin.com/uloli3/63


编辑:我找到了这个链接。希望能有所帮助。http://viralpatel.net/blogs/2011/02/clearable-textbox-jquery.html

您提到过希望它位于输入文本的右侧。所以,最好的方法是在输入框旁边创建一个图像。如果要查看方框内的内容,可以使用背景图像,但可能无法编写脚本来清除方框。

因此,插入和图像并编写JavaScript代码来清除文本框。


在输入中添加type="search" 支持是相当不错的,但将无法在IE<10

= >“搜索”型输入<


老版本浏览器

如果你需要IE9支持,这里有一些变通方法

使用标准的<input type="text">和一些HTML元素:

/** * Clearable text inputs */ $(".clearable").each(function() { const $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">&times;</i> </span> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

只使用<input class="clearable" type="text">(没有附加元素)

设置class="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/3.5.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). jQuery 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.


7x7px 动图:

Base64字符串:

data:image/gif;base64,R0lGODlhBwAHAIAAAP///5KSkiH5BAAAAAAALAAAAAAHAAcAAAIMTICmsGrIXnLxuDMLADs=

我的建议是,如果你不介意仅限于html 5兼容的浏览器,只需使用:

<input type="search" />

JS小提琴演示

不可否认,在Chromium (Ubuntu 11.04)中,这确实要求在明文图像/功能出现之前在输入元素中有文本。

参考:

深入HTML 5:一种疯狂的形式。 输入类型=搜索-搜索字段(新)HTML5。


如果你想让它像谷歌一样,那么你应该知道“X”实际上并不在<input>中——它们是彼此相邻的,外部容器样式看起来像文本框。

HTML:

<form>
    <span class="x-input">
        <input type="text" class="x-input-text" />
        <input type="reset" />
    </span>
</form>

CSS:

.x-input {
    border: 1px solid #ccc;
}

.x-input input.x-input-text {
    border: 0;
    outline: 0;
}

例如:http://jsfiddle.net/VTvNX/


下面是一个jQuery插件(最后还有一个演示)。

http://jsfiddle.net/e4qhW/3/

我这样做主要是为了说明一个例子(也是一个个人挑战)。虽然点赞很受欢迎,但其他答案都很准时,值得他们应有的认可。

然而,在我看来,这是过度设计的膨胀(除非它成为UI库的一部分)。


由于没有一个解决方案能够真正满足我们的需求,我们想出了一个简单的jQuery插件,叫做jQuery- clearsearch -

使用它就像:

<input class="clearable" type="text" placeholder="search">

<script type="text/javascript">
    $('.clearable').clearSearch();
</script>

​ 例如:http://jsfiddle.net/wldaunfr/FERw3/


我已经使用jQuery和bootstrap编写了一个简单的组件。 试试吧:https://github.com/mahpour/bootstrap-input-clear-button


不需要包含CSS或图像文件。不需要包含整个沉重的jQuery UI库。我写了一个轻量级的jQuery插件,为你做的魔法。你所需要的只是jQuery和插件。=)

jQuery InputSearch演示。


使用jquery插件,我已经适应了我的需要,添加自定义选项和创建一个新的插件。你可以在这里找到它: https://github.com/david-dlc-cerezo/jquery-clearField

下面是一个简单用法的例子:

<script src='http://code.jquery.com/jquery-1.9.1.js'></script>
<script src='http://code.jquery.com/ui/1.10.3/jquery-ui.js'></script>
<script src='src/jquery.clearField.js'></script>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css">
<link rel="stylesheet" href="css/jquery.clearField.css">

<table>
    <tr>
        <td><input name="test1" id="test1" clas="test" type='text'></td>
        <td>Empty</td>
    </tr>
    <tr>
        <td><input name="test2" id="test2" clas="test" type='text' value='abc'></td>
        <td>Not empty</td>
    </tr>
</table>

<script>
    $('.test').clearField();
</script>

获得像这样的东西:


我已经在CSS中创建了一个可清除的文本框。它不需要javascript代码使其工作

下面是演示链接

http://codepen.io/shidhincr/pen/ICLBD


jQuery Mobile现在内置了:

<input type="text" name="clear" id="clear-demo" value="" data-clear-btn="true">

Jquery移动API TextInput文档


根据MDN, <input type="search" />目前在所有现代浏览器中都被支持:

<输入类型=“搜索”=“清除此”。/>


但是,如果你想要在不同浏览器中保持一致的不同行为,这里有一些轻量级的替代方案,只需要JavaScript:

选项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>&times;</span> </div> <div class="clearable-input"> <input type="text" value="Clear this." /> <span data-clear-input>&times;</span> </div>

选项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>&times;</span> </div> <div class="clearable-input"> <input type="text" value="Clear this." /> <span data-clear-input>&times;</span> </div>

选项3 -如果输入元素有值,只显示'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>&times;</span> </div> <div class="clearable-input"> <input type="text" value="Clear this." /> <span data-clear-input>&times;</span> </div>


像这样的事情?? 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">&cross;</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>

<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>

您可以使用这些命令(没有引导)。

Array.from(document.querySelectorAll('.search-field')).forEach(field => { field.querySelector('span').addEventListener('click', e => { field.querySelector('input').value = ''; }); }); :root { --theme-color: teal; } .wrapper { width: 80%; margin: 0 auto; } div { position: relative; } input { background:none; outline:none; display: inline-block; width: 100%; margin: 8px 0; padding: 13px 15px; padding-right: 42.5px; border: 1px solid var(--theme-color); border-radius: 5px; box-sizing: border-box; } span { position: absolute; top: 0; right: 0; margin: 8px 0; padding: 13px 15px; color: var(--theme-color); font-weight: bold; cursor: pointer; } span:after { content: '\2716'; } <div class="wrapper"> <div class="search-field"> <input placeholder="Search..." /> <span></span> </div> </div>


使用简单的绝对定位——这并不难。

jQuery:

$('span').click(function(){ $('input', $(this).parent()).val(''); }) <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div style="position:relative; width:min-content;"> <input> <span style="position:absolute;right:10px">x</span> </div> <div style="position:relative; width:min-content;"> <input> <span style="position:absolute;right:10px">x</span> </div> <div style="position:relative; width:min-content;"> <input> <span style="position:absolute;right:10px">x</span> </div>

香草JS:

var spans = document.getElementsByTagName("span"); function clickListener(e) { e.target.parentElement.getElementsByTagName("input")[0].value = ""; } for (let i = 0; i < spans.length; i++) { spans[i].addEventListener("click", clickListener); } <div style="position:relative; width:min-content;"> <input> <span style="position:absolute;right:10px">x</span> </div> <div style="position:relative; width:min-content;"> <input> <span style="position:absolute;right:10px">x</span> </div> <div style="position:relative; width:min-content;"> <input> <span style="position:absolute;right:10px">x</span> </div>


在设计模式下将文本框类型更改为'search'或

<input type="search">