问题:
When I click on button the search input is in focus, but I want focus disappear on second click. Here is my code:
// Search Button
$("#mob-search-btn").click(functio...
可以将文章内容翻译成中文,广告屏蔽插件会导致该功能失效:
问题:
When I click on button the search input is in focus, but I want focus disappear on second click. Here is my code:
// Search Button
$("#mob-search-btn").click(function() {
$(".search-container input").focus();
});
I found this on w3 schools but I need this work only with one button. https://www.w3schools.com/jquery/tryit.asp?filename=tryjquery_event_focus_blur_trigger
Hope to get help from you folks.
回答1:
You need to check if the specified input has focus before deciding what to do:
Solution 1 (https://jsfiddle.net/azbnmuL9/3/):
( function($) {
$('.search-container input').focus( function() {
$(this).addClass('has-focus');
});
$( '#mob-search-btn' ).click( function() {
var el = $( '.search-container input' );
if(el.hasClass('has-focus')) {
el.blur();
el.removeClass('has-focus');
} else {
el.focus();
}
} );
} )(jQuery);
Drawback: Won't do you any good if you manually change focus to something else.
Solution 2 (https://jsfiddle.net/azbnmuL9/):
( function($) {
$( '#mob-search-btn' ).mousedown( function(e) {
e.preventDefault();
var el = $( '.search-container input' );
if(el.is(':focus')) {
el.blur();
} else {
el.focus();
}
} );
} )(jQuery);
Drawback: e.preventDefault();
prevents the button from clicking (submitting the form or whatever).
回答2:
If I understand what you're saying, you want a single, same button that focuses on the first click and defocuses on the second click and so forth. To do that, simply store a control variable:
var focused = false;
$("#mob-search-btn").click(function()
{
if (focused == true)
{
$(".search-container input").blur();
focused = false;
}
else
{
$(".search-container input").focus();
focused = true;
}
});
回答3:
You need to toggle the focus of input on every click. So a condition is required to check if the input is already focused.
var checkfocus = false;
$("#mob-search-btn").on('click', function()
{
if(checkfocus){
checkfocus = false;
$("#mob-search-btn").blur();
}
else{
checkfocus = true;
$("#mob-search-btn").focus();
}
});
回答4:
Use a flag to over come this use , focus event will not work for this scenario
let isFocus=false;
$("#mob-search-btn").click(function() {
if(isFocus){
$(".search-container").blur();
isFocus=false;
}
else{
$(".search-container").focus();
isFocus=true;
}
});
You can also use double click event to prevent this scenario if necessary
回答5:
In order to change when the input is blurred, you need to create a second click handler, e.g:
// Replace .my-button with your class or ID.
$(".my-button").click(function() {
$(".search-container input").blur();
});
By the way, it's pretty much standard convention now to use .on
rather than .click
:
$(".my-button").on("click", function() {
$(".search-container input").blur();
});