我有以下代码http://jsbin.com/bebug/7/edit?html,css,js,output。如果我们输入输入,它将显示清除按钮。但是当输入不集中时,清除按钮应该消失。仅在输入集中且输入框中有值时才应显示
的HTML
<h1>Clear icon inside Input field</h1>
<input class="clearable" type="text" name="" value="" placeholder="Enter a Search term" />
的CSS
.clearable {
background: #fff url(data:image/gif;
base64, R0lGODlhBwAHAIAAAP///5KSkiH5BAAAAAAALAAAAAAHAAcAAAIMTICmsGrIXnLxuDMLADs=) 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;
}
.clearable.onX {
cursor: pointer;
}
JS
jQuery(function ($) {
// CLEARABLE INPUT
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();
});
});
更改CSS
.clearable.x
到
.clearable.x:focus
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句