Очистить значок внутри входного текста
есть ли быстрый способ создать элемент ввода текста со значком справа, чтобы очистить сам элемент ввода (например, поле поиска google)?
Я посмотрел вокруг, но я нашел только как поставить значок в качестве фона элемента input. Существует ли плагин jQuery или что-то еще?
Я хочу значок внутри входного текстового элемента, что-то вроде:
--------------------------------------------------
| X|
--------------------------------------------------
19 ответов:
добавить a
type="search"ваши предложения
Поддержка довольно приличная, но будет не работает в IE<input type="search">
очищаемый вход для старых браузеров
если вам нужно поддержка IE9 вот некоторые обходные пути
используя стандартный
<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>используя только a
<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/2.1.1/jquery.min.js"></script>фокус в том, чтобы установить некоторые правильные отступы (я использовал 18px) в
inputи нажмите на фоновое изображение справа, с глаз долой (я использовалright -10px center).
Это заполнение 18px предотвратит скрытие текста под значком (в то время как он виден).
jq не добавим классx(еслиinputимеет значение) показывает четкую иконку.
Теперь все, что нам нужно, это нацелиться на jq входы с классомxи обнаружить наmousemoveесли мышь находится внутри этой области 18px "x"; если внутри, добавьте классonX.
Щелчок наonXкласс удаляет все классы, сбрасывает входное значение и скрывает значок.
7x7px gif:
строка Base64:
data:image/gif;base64,R0lGODlhBwAHAIAAAP///5KSkiH5BAAAAAAALAAAAAAHAAcAAAIMTICmsGrIXnLxuDMLADs=
могу ли я предложить, если вы согласны с тем, что это ограничено браузерами, совместимыми с html 5, просто используя:
<input type="search" />по общему признанию, в Chromium (Ubuntu 11.04) это требует наличия текста внутри
inputэлемент до появится четкое текстовое изображение / функциональность.ссылки:
вы можете использовать кнопку сброса стиле с изображением...
<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
Я создал понятное текстовое поле только в CSS. Он не требует кода javascript, чтобы заставить его работать
ниже приведена демо-ссылка
согласно MDN,
<input type="search" />в настоящее время поддерживается во всех современных браузерах:<input type="search" value="Clear this." />
однако, если вы хотите другое поведение, которое согласовано в разных браузерах, вот некоторые легкие альтернативы, которые требуют только 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>×</span> </div> <div class="clearable-input"> <input type="text" value="Clear this." /> <span data-clear-input>×</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>×</span> </div> <div class="clearable-input"> <input type="text" value="Clear this." /> <span data-clear-input>×</span> </div>Вариант 3-отображать только 'x', если
inputэлемент имеет значение: (пример)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>
поскольку ни одно из решений, летающих вокруг, не соответствовало нашим требованиям, мы придумали простой плагин jQuery под названием jQuery-ClearSearch -
использовать его так же просто, как:
<input class="clearable" type="text" placeholder="search"> <script type="text/javascript"> $('.clearable').clearSearch(); </script> Пример: http://jsfiddle.net/wldaunfr/FERw3/
EDIT: Я нашел эту ссылку. Надеюсь, это поможет. http://viralpatel.net/blogs/2011/02/clearable-textbox-jquery.html
вы упомянули, что хотите его справа от входного текста. Таким образом, лучшим способом было бы создать изображение рядом с полем ввода. Если вы ищете что-то внутри коробки, вы можете использовать фоновое изображение, но вы не можете написать сценарий, чтобы очистить поле.
Итак, вставьте и изображение и напишите код JavaScript очистите текстовое поле.
Если вы хотите его, как Google, то вы должны знать, что "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/
что-то вроде этого??
Jsfiddle Demo<!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>
вот плагин jQuery (и демо в конце).
Я сделал это в основном для иллюстрации пример (и личный вызов). Хотя upvotes приветствуются, другие ответы хорошо раздаются вовремя и заслуживают их должного признания.
тем не менее, на мой взгляд, он чрезмерно спроектирован (если он не является частью библиотеки пользовательского интерфейса).
Я написал простой компонент с помощью jQuery и bootstrap. Дайте ему попробовать: https://github.com/mahpour/bootstrap-input-clear-button
используя плагин 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>получение чего-то вроде этого:
jQuery Mobile теперь имеет этот встроенный:
<input type="text" name="clear" id="clear-demo" value="" data-clear-btn="true">
нет необходимости включать CSS или файлы изображений. Не нужно включать, что вся тяжелая артиллерия библиотеки пользовательского интерфейса jQuery. Я написал легкий плагин jQuery, который делает чудеса для вас. Все, что вам нужно-это
jQueryи плагин. =)скрипку здесь: в jQuery InputSearch демо.
<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>





Comments
I came across a 175 very cool page that I think you should dive into.
This platform is packed with a lot of useful information that you might find valuable.
It has everything you could possibly need, so be sure to give it a visit!
<a href="https://theportablegamer.com/2025/02/20/turn-your-smartphone-into-a-psp-with-these-must-have-accessories/">https://theportablegamer.com/2025/02/20/turn-your-smartphone-into-a-psp-with-these-must-have-accessories/</a>
And don't forget, everyone, which one at all times can in the article discover solutions to address the most the very tangled queries. Our team tried — lay out all of the information using the extremely easy-to-grasp way.