带有清除按钮的文本输入,自动隐藏和显示

时间:2017-05-21 17:01:17

标签: javascript html

我正在使用搜索框的网站上工作,在搜索输入字段中,我想设置一个重置按钮“X”

因此,当搜索框输入字段为空时,它不会显示“X”。但是当用户在字段内键入任何内容时,“X”将自动显示。

同样,当用户点击“X”时,它会清除所有类型的数据并仍然集中在输入字段内?

直到现在我已经完成了这个

只有JAVASCRIPT代码我不使用jQuery!

var searchSminput = document.getElementById("offcansearch").value.length;

if (searchSminput == 0) {
document.getElementById("resetb").style.display = "none";
} else {
document.getElementById("resetb").style.display = "block";
}
	#resetb {
		
		background-image: url(http://cdn.onlinewebfonts.com/svg/img_286433.svg);
		background-repeat: no-repeat;
		background-size: 22px 42px;
		cursor: pointer;
		display: block;
		transition: all 300ms ease;
		width: 22px;
		height: 42px;
		border: none;
		background-color: transparent;
		outline: none;
		right: 10px;
		top: 5px;
		position: absolute;
		margin: 0;
		padding: 0;
	}	
  #offcansearch {
  width: 100%;
  height: 30px;
  }
<form>
<input id="offcansearch" type="text" name="search" placeholder="Search">
<button id="resetb" type="reset"></button>
</form>

1 个答案:

答案 0 :(得分:1)

向输入添加更改事件:

document.getElementById('offcansearch').addEventListener('change', function() { ... }

同时添加到重置按钮(单击时隐藏按钮):

resetb.addEventListener('click', function() {
  resetb.style.display = "none";
});

&#13;
&#13;
var resetb =  document.getElementById("resetb");
var offcansearch = document.getElementById('offcansearch');

offcansearch.addEventListener('keyup', function() {
  var searchSminput = offcansearch.value.length;
  if (searchSminput == 0) {
    resetb.style.display = "none";
  } else {
    resetb.style.display = "block";
  }
});

resetb.addEventListener('click', function() {
  resetb.style.display = "none";
  offcansearch.focus();
});
&#13;
#resetb {
  background-image: url(http://cdn.onlinewebfonts.com/svg/img_286433.svg);
  background-repeat: no-repeat;
  background-size: 22px 42px;
  cursor: pointer;
  display: none;
  transition: all 300ms ease;
  width: 22px;
  height: 42px;
  border: none;
  background-color: transparent;
  outline: none;
  right: 10px;
  top: 5px;
  position: absolute;
  margin: 0;
  padding: 0;
}

#offcansearch {
  width: 100%;
  height: 30px;
}
&#13;
<form>
  <input id="offcansearch" type="text" name="search" placeholder="Search">
  <button id="resetb" type="reset"></button>
</form>
&#13;
&#13;
&#13;