2017-08-22 87 views
1

我试图让一个字段在盘旋时集中,但仅在3秒钟的延迟之后。显然,我做错了:使用jQuery将焦点悬停后的字段悬停

var timer; 
 

 
function focusTimer() { 
 
    timer = setTimeout(function() { 
 
     $('#input').focus(), 
 
     3000; 
 
    }) 
 
} 
 

 
$('#input').hover(function() { 
 
    if (timer) { 
 
     clearTimeout(timer); 
 
    } 
 
    
 
    focusTimer(); 
 
});
#input:focus { 
 
    width: 500px; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<input id="input">

回答

4

你做错了。

你正在把3000放在函数里面。它向外侧移动

timer = setTimeout(function() { 
     $('#input').focus(), 
     3000; 
     ^^^^^^^ 
    }) 

应该

timer = setTimeout(function() { 
     $('#input').focus(); 
    },3000); 

片段

var timer; 
 

 
function focusTimer() { 
 
    timer = setTimeout(function() { 
 
     $('#input').focus(); 
 
     
 
    },3000) 
 
} 
 

 
$('#input').hover(function() { 
 
    if (timer) { 
 
     clearTimeout(timer); 
 
    } 
 
    
 
    focusTimer(); 
 
});
#input:focus { 
 
    width: 500px; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<input id="input">

2

使用过渡延迟

#input { 
    -webkit-transition-delay: 5s; 
    transition:width 5s; 
    transition-delay:5s; 
    width:100px; 
} 

#input:focus { 
    width:200px; 
} 

悬停在输入:

#input:hover { 
width:200px; 
} 
+1

gread CSS溶液。 +1那个 –

+1

我也是。 +1的思考方框。 –

+0

无视,得到它的工作。但是,这并不是我想要的。上面的JS方法将鼠标悬停一段时间之后的输入为重点。这需要点击输入。 – Tohuw

2

var timer; 
 

 
function focusTimer() { 
 
    timer = setTimeout(function() { //change your setTimeout like this 
 
     $('#input').focus(); 
 
     
 
    },3000); 
 

 
    
 
} 
 

 
$('#input').hover(function() { 
 
    if (timer) { 
 
     clearTimeout(timer); 
 
    } 
 
    
 
    focusTimer(); 
 
});
#input:focus { 
 
    width: 500px; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<input id="input">

1

$("#i").hover(function() { 
 
    setTimeout(function() { 
 
    $("#i").focus(); 
 
    }, 1000); 
 
}) 
 

 
#i { 
 
    width:300px; 
 
    transition:width 1s; 
 

 
#i:focus { 
 
    width: 500px; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<input type="text" id="i">

+0

我喜欢这里的功能简洁。 – Tohuw