当父容器打开类时,尝试获取一个要聚焦的输入。
到目前为止,我的代码是:
$("#search-trigger").click(function(){
$("input").focus();
});
它只在元素开始关闭时才能正常工作。所以,我把它改为:
$("#search-trigger").click(function(){
if(("#target-2").hasClass("open")){
$("input").focus();
}else{
$("input").blur();}
});
根本不起作用。有什么想法吗?
科德芬
发布于 2016-10-20 23:35:05
我认为这里的主要问题是输入没有完成动画,所以jQuery不能专注于它。解决方案是在目标显示后使用TweenMax的onComplete
事件来聚焦元素。
不过,请注意,您最初的问题并没有包含动画代码,所以如果其他人不愿意查看您的CodePen,他们就无法提供帮助。
下面是我制作的新JavaScript,但是您只需修改原始代码就可以使用onComplete
函数:
$('.trigger').click(function(e) {
//remove active class from other triggers
$('.trigger').not(this).removeClass('active');
//toggle active class on this trigger
$(this).toggleClass('active');
//get target element
var target = $('#' + $(this).attr('data-target-id'));
//hide all elements of target class, except the current target
if($('.target.open').not(target).size() > 0) {
TweenMax.to($('.target.open').not(target), .2, {display:'none', y:'0%', autoAlpha:0});
//remove open class from target elements that are now hidden
$('.target.open').not(target).removeClass('open');
}
//if this element is now active
if($(this).hasClass('active')) {
//show current target element
TweenMax.to(target, .2, {display:'block', y:'100%', autoAlpha:1, onComplete:function() {
//once animation is complete, if the target has an input, focus on that input
if(target.find('input').size() > 0) {
target.find('input').focus();
}
}});
//indicate that this target class element is now open
target.addClass('open');
}
//if the element is no longer active
else {
//hide the target
TweenMax.to(target, .2, {display:'none', y:'0%', autoAlpha:0});
//remove open class from newly hidden target element
target.removeClass('open');
}
});
这里有一个CodePen在你的背上:http://codepen.io/anon/pen/qaLkYo
发布于 2016-10-20 23:39:41
I 更新您的CodePen。
你的动画正在进行中..。
我没有仔细检查它是如何实现的,因为一个外部库(TweenMax)正在这样做。
但是,看到动画,我想到了延迟。
这就是我的答案。
不能将focus
设置为display
的元素设置为none
。
此显示由您的动画设置为block
或inline-block
.
我发现在这种情况下,延迟10毫秒是不可能的。
为了确保我们选择了正确的input
,因为即使在那个例子中只有一个.您的网站将有更多的肯定。
我指定它是单击元素的同级的子元素。
以下是相关代码:
// This is the code for the input focus
$("#search-trigger").click(function(){
var searchInput = $(this).siblings().find("input");
setTimeout(function(){
searchInput.focus();
},10);
});
发布于 2016-10-20 23:05:28
如果页面上有许多输入,而不是给出特定的输入,那么您想要集中ID并按ID调用它,如下所示:
$("input#my-input").focus();
https://stackoverflow.com/questions/40165845
复制相似问题