我想在文本字段中添加一个清除按钮,该文本字段在输入中的文本之后浮动。使用搜索类型输入字段有一种简单的方法吗?
<input type="search">
答案 0 :(得分:0)
您可以使用JavaScript将输入的文本复制到隐藏的<span>
中,然后根据<span>
的宽度移动重置按钮。 (这受https://stackoverflow.com/a/14855810/3469273启发。)
var search = document.getElementById("search"),
reset = document.getElementById("reset"),
measure = document.getElementById("measure");
search.addEventListener("input", onInput);
reset.addEventListener("click", onInput);
function onInput() {
measure.textContent = this.value;
reset.style.left = measure.offsetWidth + 'px';
console.log(measure.offsetWidth);
};
&#13;
form {
position: relative;
margin: 1rem;
}
#search,
#measure {
padding: .5rem;
font-family: sans-serif;
font-size: 1rem;
white-space: pre; /* white-spaces will work effectively */
}
#search {
width: 100%;
}
#reset {
position: absolute;
left: 0;
top: 0;
height: 100%;
background: transparent;
border: none;
color: #999;
cursor: pointer;
}
#measure {
position: absolute;
left: -9999px;
top: -9999px;
}
&#13;
<form>
<input id="search" type="search" />
<input id="reset" type="reset" value="X">
</form>
<span id="measure"></span>
&#13;
答案 1 :(得分:0)
我想你想要一个按钮来清除输入的内容 以下是要求的代码:
<input id = "inputBox" class="inputBox" type="search">
<button class="clear-button" onclick="myfunction()">Clear</button>
<script>
function myfunction(){
document.getElementById("inputBox").value = ""
}
</script>