CSS: Change parent on focus of child

前端 未结 4 849
日久生厌
日久生厌 2020-12-13 01:43

Let\'s say you have something like:

<
相关标签:
4条回答
  • 2020-12-13 01:57

    There is no chance how to do that with CSS. CSS can style only siblings, children, etc. not parents.

    You can use simply JS like this:

    <style>
    .parent {background: green}
    .focused {background: red;}
    </style>
    <div class="parent">
        <input class="childInput" type="text" />
        <div class="sibling"></div>
    </div>
    
    <script>
    $('.parent > *')
        .focus(function() {
            $('.parent').addClass('focused');
        })
        .blur(function() {
            $('.parent').removeClass('focused');
        });
    </script>
    

    http://jsfiddle.net/C4bZ6/

    This code takes all direct children of .parent and if you focus one of them, class focused is added to parent. On blur, this class is removed.

    0 讨论(0)
  • 2020-12-13 02:11

    You can now do this in pure CSS, so no JavaScript needed

    0 讨论(0)
  • 2020-12-13 02:11

    You can use pure CSS to make the text input look like it's not a text input unless it is in focus

    http://jsfiddle.net/michaelburtonray/C4bZ6/13/

    input[type="text"] {
        border-color: transparent;
        transition-duration: 600ms;
        cursor: pointer;
        outline-style: none;
        text-overflow: ellipsis;
    }
    
    input[type="text"]:focus {
        border-color: initial;
        cursor: auto;
        transition-duration: 300ms;
    }
    
    0 讨论(0)
  • 2020-12-13 02:14

    Try the contenteditible attribute. This may require more work to turn it into usable form data however.

    http://jsfiddle.net/michaelburtonray/C4bZ6/20/

    <span class="parent" contenteditable>Click me</span>
    
    0 讨论(0)
提交回复
热议问题