I have a button with toggleClass
and setTimeout
function, currently it is working based on the written script but I do not need delay on first click. Hide div quickly and display with some delay. Now both delay timings are same. Can anyone help !
$(document).ready(function() {
$(".button").click(function() {
window.setTimeout(function() {
$(".search").toggleClass("hide");
}, 250);
});
});
.hide {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<button class="button" type="button">nav</button>
<div class="search"><input type="text" placeholder="Search"></div>
答案 0 :(得分:5)
从未使用过jquery,但这应该可以工作,不确定是否是最干净的解决方案。
$(document).ready(function() {
$(".button").click(function() {
if($(".search").hasClass("hide"))
{
window.setTimeout(function() {
$(".search").toggleClass("hide");
}, 250);
}
else $(".search").toggleClass("hide");
});
});
.hide {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<button class="button" type="button">nav</button>
<div class="search"><input type="text" placeholder="Search"></div>
答案 1 :(得分:1)
检查元素是否可见或隐藏,然后决定要做什么:
$(document).ready(function() {
$(".button").click(function() {
if ($(".search").is(":visible")){
$(".search").addClass("hide");
}
else{
window.setTimeout(function() {
$(".search").toggleClass("hide");
}, 250);
}
});
});
.hide {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<button class="button" type="button">nav</button>
<div class="search"><input type="text" placeholder="Search"></div>
答案 2 :(得分:1)
如何使用简单的变量firstClick
,最初是true,然后是所有点击false
?
$(document).ready(function() {
var firstClick =true;
$(".button").click(function() {
window.setTimeout(function() {
firstClick=false;
$(".search").toggleClass("hide");
}, firstClick?0:250);
});
});
.hide {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<button class="button" type="button">nav</button>
<div class="search"><input type="text" placeholder="Search"></div>