2016-02-18 20 views
1

当鼠标悬停在搜索图标上时,显示一个搜索输入。 搜索图标不可点击,所以我试图在链接上添加一个onclick来触发搜索。 但是,当我在移动设备上尝试此解决方案时,由于我没有在移动设备上使用鼠标,因此当我选择搜索图标时,它会触发搜索,而不会输入任何字词。当输入选择时,在链接上添加onclick标记

下面是HTML:

<div class="search-container"> 
    <form method="get" id="searchform"> 
     <input type="text" name="s" placeholder="<?php echo $search; ?>"> 
     <a style="cursor: pointer;" class="search" onclick="document.getElementById('searchform').submit();" 
      <img src="<?php echo get_template_directory_uri(); ?>/img/search-icon.png" alt="Search" /> 
     </a> 
    </form> 
</div> 

这里是CSS:

.search-container { 
    overflow: hidden; 
    float: right; 
    width: 37px; 
    -moz-transition: width 0.35s; 
    -webkit-transition: width 0.35s; 
} 
.search-container:hover { 
    width: 20em; 
} 
.search-container:hover input { 
    display: inline-block; 
    width: 200px; 

} 

.search-container input { 
    -moz-appearance: none; 
    -webkit-appearance: none; 
    appearance: none; 
    float: left; 
    width: 0em; 
    margin-right: -42px; 
    font-size: 1em; 
    height: 35px; 
    padding: 5px; 
    border: 0; 
    color:#333; 
    -moz-transition: width 0.25s; 
    -webkit-transition: width 0.25s; 
} 
.search-container input:focus { 
    outline: none; 
} 
.search-container img { 
    float: right; 
    background-color: #df5927; 
    padding: 5px; 
} 

如何激活查找图标点击时,才显示输入?

回答

2

你可以按照不同的方式。
如果单击该图标并输入没有值,显示输入,否则提交表单

你必须移动在新功能的点击处理程序,而不是内嵌在<a>元素

所以你监听<a>元素

document.querySelector('.search').addEventListener("click", handleClick); 

,然后在点击时,一个点击,你检查输入具有任何价值,要么提交或显示实际输入

function handleClick(event){ 
    var input = document.querySelector("input[name='s']"); 
    if(input.value.length == 0){ 
    //dont submit and show input for mobile 
    } else { 
    // input has value, submit form 
    document.getElementById('searchform').submit(); 
    } 
} 
+0

感谢您的回答,它完美适用于Android手机和PC,但是,Iphone有问题。在输入中填充文本时,点击不是句柄,真的很奇怪 –

+0

@MarcElBichon在扩展输入时能看到一些元素是否与图标重叠吗? – eltonkamami

+0

nop,但经过一些测试后,这个问题似乎只在iphone 5上。这很奇怪,但我可以离开,谢谢你的时间。 –