3功能1输入

时间:2016-11-05 14:54:17

标签: javascript html

我创建了一个搜索框,当搜索到“按钮”(输入)时,它应该打开和关闭。问题是,当我想要关闭搜索框时,我必须单击两次并在同一点(x,y轴必须是相同的,否则函数提交结果)。

function slideOpen(elopen){
    var elem = document.getElementById(elopen);
    elem.style.transition = "width 1.4s ease-in-out"
    elem.style.width = "250px";
    elem.style.height = "50px";
}
    
function slideClosed(elclose){
    var elem = document.getElementById(elclose)
    elem.style.transition = "width 1.4s ease-in-out"
    elem.style.width = "0px";
    elem.style.height = "50px"; 
    elem.style.border = "0";
    elem.style.padding = "10px 25px 10px 25px";
    
}
    
function searchbutton(){
    var typetext = document.getElementById("typetext");
    var typetextWidth = document.getElementById("typetext").getAttribute("width");
    var onClick = document.getElementById("searchtext").onclick; 
    if(typetextWidth === "0"){
    onClick = slideOpen('typetext');
    
    } else {
    onClick = slideClosed('typetext');
    }
         
}
<form>
      <input id="typetext" type="text" name="search" placeholder="Patience is a virtue" />
     <input id="searchtext" type="image" src="search.png" onclick="searchbutton()"  />
      
    </form>

1 个答案:

答案 0 :(得分:0)

如果您对全局变量没有问题,那么我认为这样做会更好:

...
var searchIsShown = false;

function searchbutton(){

    if(searchIsShown)
    {
        searchIsShown = false;
        slideOpen('typetext');
    } else {
        searchIsShown = true;
        slideClosed('typetext');
    }

}

另外,您应该将heighttransition移至CSS