jQuery 切换焦点/模糊
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5608181/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery toggle focus / blur
提问by hubrid
How can I toggle an element's CSS on focus/blur with jQuery?
如何使用 jQuery 在焦点/模糊上切换元素的 CSS?
$('.answerSpace').bind('blur', function(){
$('.normProf').toggleClass('opacProf');
});
$('.answerSpace').bind('focus', function(){
$('.opacProf').toggleClass('normProf');
});
So now I have this. But it doesn't quite work...
所以现在我有了这个。但这并不完全有效...
回答by vsync
Check this out, it's exactly how y'all should do jQuery focus toggle..
看看这个,这正是你们应该如何进行 jQuery 焦点切换的方式..
Basic use case:
基本用例:
$('input').on('focus blur', toggleFocus);
function toggleFocus(e){
console.log(e.type)
if( e.type == 'focusin' ){
// do something on focus
}
else{
// do something else on blur
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input>
回答by mattsven
Try
尝试
$('.answerSpace').bind('blur', function(){ $('.normProf').removeClass("normProf").addClass('opacProf'); });
$('.answerSpace').bind('focus', function(){ $('.opacProf').removeClass("opacProf").addClass('normProf'); });
回答by bluefoot
Well, if I get you right, you can use onblurand onfocusevents, with the toggleClassfunction:
好吧,如果我没听错的话,你可以使用onblur和onfocus事件,以及toggleClass函数:
$('#yourelement').bind('blur', function(){
$(this).toggleClass('your-class');
});
$('#yourelement').bind('focus', function(){
$(this).toggleClass('your-class');
});
回答by TheCrazyProfessor
Blur is only get active when you leave a input, so you can use it to remove the focus again.
模糊仅在您离开输入时才被激活,因此您可以使用它再次移除焦点。
$('input').focus(function(){
$(this).css('box-shadow', '0px 0px 1px #ccc');
});
$('input').blur(function(){
$(this).css('box-shadow', 'none');
});