开发者

jQuery toggle focus / blur

How can I toggle an element's CSS on focus/blur with jQuery?

$('.answerSpace').bind('blur', function(){
$('.normProf').tog开发者_Go百科gleClass('opacProf');
});

$('.answerSpace').bind('focus', function(){
    $('.opacProf').toggleClass('normProf');
});

So now I have this. But it doesn't quite work...


Check this out, it's exactly how y'all should do jQuery focus toggle..

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>


Try

$('.answerSpace').bind('blur', function(){ $('.normProf').removeClass("normProf").addClass('opacProf'); });
$('.answerSpace').bind('focus', function(){ $('.opacProf').removeClass("opacProf").addClass('normProf'); });


Well, if I get you right, you can use onblur and onfocus events, with the toggleClass function:

$('#yourelement').bind('blur', function(){
    $(this).toggleClass('your-class');
});

$('#yourelement').bind('focus', function(){
    $(this).toggleClass('your-class');
});


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');
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜