Anyway to have a label respond to :focus CSS

后端 未结 3 1273
一生所求
一生所求 2020-12-20 11:22

Is there any way to have a label respond to focus. I have some code where the textfield has a different style on focus. The label also however needs a slightly different sty

3条回答
  •  星月不相逢
    2020-12-20 12:00

    BoltClock's answer is the more semantic, lightweight way of achieving this functionality. However it's not always possible to have a specific HTML structure (especially to facilitate a minor feature like this) and CSS lacks the ability to traverse up the HTML hierarchy. To get around that, here are two alternatives. The first is coming soon (CSS spec 4) and the second is our old mate Javascript.

    First up, CSS4's :focus-within pseudo selector. This does exactly what it says on the tin (scopes based on any child element's active focus state). Read more about the spec here. So assuming you have a HTML structure of:

    you could scope the 'focussed' label by simply:

    label:focus-within{}
    

    by the same token, you could also scope the parent div with:

    div.input-wrapper:focus-within{}
    

    Magical. But not for use today :(

    Second up, if you're already using a JS selector engine (i.e. jQuery, Sizzle, etc.), you could also do something along the lines of:

    $('input').on("focus", function(){
      var input = $(this);
      // assuming label is the parent, i.e. 
      var label = $(this).parent();
      label.addClass('focussed');
      input.on("blur", function(){
        label.removeClass('focussed');
        input.off("blur");
      });
    });
    

    This is untested but the essence of what this achieves is using a class rather than the :focus pseudo selector. So you can add your focussed styles to label.focussed{}. I've added (and self-removed) the blur handler to facilitate removing the class.

提交回复
热议问题