我有一个很棒的脚本,用于在搜索框中添加'x'。如果我从头开始输入一些东西,它就会工作,但如果文本已经存在(比如在查看搜索结果后单击返回),"x"就不存在了。什么好主意吗?
JSFiddle
<input type="search" class="clearable" value="Some search text" placeholder="Search">
<script>
jQuery(function ($) {
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('click', '.onX', function () {
$(this).removeClass('x onX').val('');
});
});
</script>
<style>
.clearable {
background:url(http://i.imgur.com/z7ZSYjt.png) no-repeat right -10px center;
padding:3px 18px 3px 4px;
border-radius:3px;
transition: background 0.4s;
}
.clearable.x {
background-position: right 5px center;
}
.clearable.onX {
cursor:pointer;
}
</style>
也许尝试悬停,而不是鼠标移动?
function tog(v) {
return v ? 'addClass' : 'removeClass';
}
$(document).on('input', '.clearable', function () {
$(this)[tog(this.value)]('x');
}).on('hover', '.x', function (e) {
$(this)[tog(this.offsetWidth - 18 < e.clientX - this.getBoundingClientRect().left)]('onX');
}).on('click', '.onX', function () {
$(this).removeClass('x onX').val('');
});
});