我创建的输入带有清除输入文本的图标。
我最初将其设置为显示:无。 当您专注于输入时,会出现我想要的清除图标,但是当您单击清除图标时,它会消失并且不会清除输入文本,但是只有当您再次专注于输入时才重新出现,我不想之所以这样做,是因为只有在您单击输入之外,它才应该保持可见,然后它应该隐藏...
所以用例应该是:
我的脚本无法正常工作,我尝试了多种方法自行解决,但不,无法解决。
$("input")
.focus(function() {
$(this).attr("placeholder", "enter your email address...");
$(".material-icons").show();
})
.blur(function() {
$(".material-icons").hide();
$(this).attr("placeholder", "input here");
$(".clear-input").click(function() {
$(this).prev().val("").focus();
});
});
html {
box-sizing: border-box;
}
form {
margin: 20vh;
}
.container {
border: none;
width: 248px;
position: relative;
}
input {
border: 1px solid pink;
box-shadow: none;
padding: 8px 100px 8px 5px;
position: relative;
}
input:hover {
border: 1px solid #222;
}
input:focus {
border: 1px solid blue;
}
.material-icons {
position: absolute;
right: 0px;
top: 0px;
margin: auto;
font-size: 3px;
cursor: pointer;
color: #aaa;
padding: 8px;
display: none;
}
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<div class="container">
<input class="type-here" type="text" placeholder="input here" />
<i class="clear-input material-icons">clear</i>
</div>
</form>
答案 0 :(得分:1)
只需将click更改为mousedown,因为模糊会比click事件更早触发,并删除click事件并将click事件置于焦点事件中。
$(document).ready(function(){
$(".material-icons").hide();
$("input")
.focus(function() {
$(this).attr("placeholder", "enter your email address...");
$(".material-icons").show();
$(".clear-input").mousedown(function(e) {
e.preventDefault();
$(this).prev().val("");
});
})
.blur(function() {
$(".material-icons").hide();
$(this).attr("placeholder", "input here");
});
});
html {
box-sizing: border-box;
}
form {
margin: 20vh;
}
.container {
border: none;
width: 248px;
position: relative;
}
input {
border: 1px solid pink;
box-shadow: none;
padding: 8px 100px 8px 5px;
position: relative;
}
input:hover {
border: 1px solid #222;
}
input:focus {
border: 1px solid blue;
}
.material-icons {
position: absolute;
right: 0px;
top: 0px;
margin: auto;
font-size: 3px;
cursor: pointer;
color: #aaa;
padding: 8px;
}
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<div class="container">
<input class="type-here" type="text" placeholder="input here" />
<i class="clear-input material-icons">clear</i>
</div>
</form>
答案 1 :(得分:1)
这是一个不太优雅的解决方案:
$("input").focus(function() {
$(this).attr("placeholder", "enter your email address...");
$(".material-icons").show();
});
$('body').click(function(e){
if ( !$(e.target).is('input') && !$(e.target).is('.material-icons') ) {
$(".material-icons").hide();
}
});
$('.clear-input').click(function(){
$('input').val('')
});