gpt4 book ai didi

javascript - 选择输入时在链接上添加 onclick 标签

转载 作者:行者123 更新时间:2023-11-30 16:16:20 25 4
gpt4 key购买 nike

我有一个搜索输入,当鼠标悬停在搜索图标上时会显示该输入。搜索图标不可点击,所以我尝试在链接上添加一个 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;
}

如何仅在显示输入时激活对搜索图标的点击?

最佳答案

您可以采用不同的方法。
如果点击图标,输入没有值,则显示输入,否则提交表单

您必须将点击处理程序移动到一个新函数中,而不是内嵌在 <a> 中元素

因此您会听到对 <a> 的点击元素

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

然后当单击 a 时,您检查输入是否有任何值并提交或显示实际输入

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();
}
}

关于javascript - 选择输入时在链接上添加 onclick 标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35476518/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com