如何制作javascript切换按钮?

时间:2016-09-07 18:23:44

标签: javascript

我有这段代码,但它不起作用:

HTML:

<button id="btn_search">Search</button>
<input id="srh" type="search">

JS:

var btnSearch = document.getElementById("btn_search");
var search = document.getElementById("srh");

if (document.addEventListener) {
   btnSeach.addEventListener('click',activeSearch);
} else if (document.attackEvent) {
   btnSearch.attackEvent('onclick',activeSearch);
}

function activeSearch (event) {
  event.preventDefault();
  if (search.style.width == '0') {
    search.style.width = '14.8em';
    search.style.opacity = '1';
} else if (search.style.width == '14.8em') {
    search.style.width = '0';
    search.style.opacity = '0';
}

我需要一个切换按钮 我该怎么办?

2 个答案:

答案 0 :(得分:1)

我可能会考虑使用CSS类和 toggle()来显示/隐藏您的元素。

&#13;
&#13;
var btnSearch = document.getElementById("btn_search");
btnSearch.addEventListener('click', function(event){
  var search = document.getElementById("srh");
  search.classList.toggle("hidden");
  event.preventDefault();
});
&#13;
#srh { width: 14.8em; }
#srh.hidden { display: none; }
&#13;
<button id="btn_search">Search</button>
<input id="srh" type="search" />
&#13;
&#13;
&#13;

答案 1 :(得分:0)

您可以简单地使用JQuery来简化所有过程。使所有代码如下:

function magictoggle(a) {
  if (a == 1) {
    $("#btn1").attr("onclick", "magictoggle(0)");
    $("#searchbox").hide(1000);
    //1000 Are the miliseconds will take the box to hide
  } else {
    $("#btn1").attr("onclick", "magictoggle(1)");
    $("#searchbox").show(1000);
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="btn1" onclick="magictoggle(1)">Search</button>
<input type="text" id="searchbox" placeholder="A search Box">