How to make javascript toggle button?

匿名 (未验证) 提交于 2019-12-03 09:06:55

问题:

I have this code but it doesn't work:

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'; } 

I need a toggle button What should I do?

回答1:

I might think about using a CSS class and toggle() to show/hide you element.

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


回答2:

You can simply use JQuery to simplify all the proccess. Make all the code as simple as:

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">


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!