Programing

: focus를 사용하여 외부 div 스타일을 지정합니까?

lottogame 2020. 12. 27. 10:16
반응형

: focus를 사용하여 외부 div 스타일을 지정합니까?


텍스트 영역에 텍스트를 쓰기 시작할 때 클래스 상자가있는 외부 div에 테두리가 점선 대신 단색으로 바뀌기를 원하지만이 경우에는 : focus가 적용되지 않습니다. : active와 함께 작동한다면, : focus와 함께 작동하지 않는 이유는 무엇입니까?

이유는 무엇입니까?

(참고. DIV의 테두리가 텍스트 영역이 아닌 단색으로 바뀌기를 원합니다.)

div.box
{
    width: 300px;
    height: 300px;
    border: thin dashed black;
}

div.box:focus{
    border: thin solid black;
}

<div class="box">
    <textarea rows="10" cols="25"></textarea>
</div>

CSS / HTML만으로는 달성 할 수 없지만 JavaScript로 달성 할 수 있습니다 (라이브러리없이).

var textareas = document.getElementsByTagName('textarea');

for (i=0;i<textareas.length;i++){
    // you can omit the 'if' if you want to style the parent node regardless of its
    // element type
    if (textareas[i].parentNode.tagName.toString().toLowerCase() == 'div') {
        textareas[i].onfocus = function(){
            this.parentNode.style.borderStyle = 'solid';
        }
        textareas[i].onblur = function(){
            this.parentNode.style.borderStyle = 'dashed';
        }
    }
}

JS Fiddle 데모 .

덧붙여서, jQuery와 같은 라이브러리를 사용하면 위의 내용을 다음과 같이 압축 할 수 있습니다.

$('textarea').focus(
    function(){
        $(this).parent('div').css('border-style','solid');
    }).blur(
    function(){
        $(this).parent('div').css('border-style','dashed');
    });

JS Fiddle 데모 .

참조 :


DIVtabindex속성을 설정하면 요소가 포커스를받을 수 있습니다 . 다음은 작동 예입니다.

#focus-example > .extra {
  display: none;
}
#focus-example:focus > .extra {
  display: block;
}
<div id="focus-example" tabindex="0">
  <div>Focus me!</div>
  <div class="extra">Hooray!</div>
</div>

에 대한 자세한 내용 focusblur, 당신은 체크 아웃 할 수있다 이 기사를 .

업데이트 : 그리고 여기 focusmenu.

#toggleMenu:focus {
  outline: none;
}
button:focus + .menu {
  display: block;
}
.menu {
  display: none;
}
.menu:focus {
  display: none;
}
<div id="toggleMenu" tabindex="0">
  <button type="button">Menu</button>
  <ul class="menu" tabindex="1">
    <li>Home</li>
    <li>About Me</li>
    <li>Contacts</li>
  </ul>
</div>


다른 포스터는 :focus의사 클래스가 부족한 이유를 이미 설명 했지만 마지막으로 CSS 기반 표준 솔루션이 있습니다.

CSS 선택기 레벨 4는 새로운 의사 클래스를 정의합니다.

: 포커스-내부

에서 MDN :

:focus-withinCSS 의사 클래스는 그 모든 요소와 일치 :focus의사 수준의 일치 또는는 그 후손이 :focus의사 클래스 일치. (여기에는 그림자 나무의 자손이 포함됩니다.)

이제 :focus-within의사 클래스를 사용하여 textarea클릭 할 때 외부 div의 스타일을 지정하는 것이 간단 해집니다.

.box:focus-within {
    border: thin solid black;
}

.box {
    width: 300px;
    height: 300px;
    border: 5px dashed red;
}

.box:focus-within {
    border: 5px solid green;
}
<p>The outer box border changes when the textarea gets focus.</p>
<div class="box">
    <textarea rows="10" cols="25"></textarea>
</div>

Codepen 데모

주의 : 브라우저 지원 : Chrome (60+), Firefox 및 Safari


:focus-within이제이 게시물에서 예 를 들어 CSS 방법 통해 달성 할 수 있습니다 . http://www.scottohara.me/blog/2017/05/14/focus-within.html

/*
  A normal (though ugly) focus
  pseudo-class.  Any element that
  can receive focus within the
  .my-element parent will receive
  a yellow background.
*/
.my-element *:focus {
  background: yellow !important;
  color: #000;
}

/*
  The :focus-within pseudo-class
  will NOT style the elements within
  the .my-element selector, like the
  normal :focus above, but will
  style the .my-element container
  when its focusable children
  receive focus.
*/
.my-element:focus-within {
  outline: 3px solid #333;
}
<div class="my-element">
  <p>A paragraph</p>
  <p>
    <a href="http://scottohara.me">
      My Website
    </a>
  </p>

  <label for="wut_email">
    Your email:
  </label>
  <input type="email" id="wut_email" />
</div>


간단한 사용 JQuery.

$(document).ready(function() {
  $("div .FormRow").focusin(function() {
    $(this).css("background-color", "#FFFFCC");
    $(this).css("border", "3px solid #555");
  });
  $("div .FormRow").focusout(function() {
    $(this).css("background-color", "#FFFFFF");
    $(this).css("border", "0px solid #555");
  });
});
    .FormRow {
      padding: 10px;
    }
<html>

<head>
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
</head>

<body>
  <div style="border: 0px solid black;padding:10px;">
    <div class="FormRow">
      First Name:
      <input type="text">
      <br>
    </div>
    <div class="FormRow">
      Last Name:
      <input type="text">
    </div>
  </div>

  <ul>
    <li><strong><em>Click an input field to get focus.</em></strong>
    </li>
    <li><strong><em>Click outside an input field to lose focus.</em></strong>
    </li>
  </ul>
</body>

</html>


div 태그 사이를 탭할 수 있습니다. div에 탭 인덱스를 추가하기 만하면됩니다. 이 문제를 해결하려면 jQuery 및 CSS 클래스를 사용하는 것이 가장 좋습니다. 다음은 IE, Firefox 및 Chrome에서 테스트 된 작업 샘플입니다 (최신 버전 ... 이전 버전은 테스트하지 않음).

<html>
    <head>
        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
        <script type="text/javascript">
            var divParentIdFocus;
            var divParentIdUnfocus = null;

            $(document).ready(function() {              

                    $("div").focus(function() {
                        //$(this).attr("class", "highlight");
                        var curDivId = $(this).attr("id");

                        // This Check needs to be performed when/if div regains focus
                        // from child element.
                        if (divParentIdFocus != curDivId){
                            divParentIdUnfocus = divParentIdFocus;
                            divParentIdFocus = curDivId;
                            refreshHighlight();
                        }

                        divParentIdFocus = curDivId;
                    });


                    $("textarea").focus(function(){
                        var curDivId = $(this).closest("div").attr("id");

                        if(divParentIdFocus != curDivId){
                            divParentIdUnfocus = divParentIdFocus;
                            divParentIdFocus = curDivId;
                            refreshHighlight();
                        }
                    });

                    $("#div1").focus();
            });

            function refreshHighlight()
            {
                if(divParentIdUnfocus != null){
                    $("#" +divParentIdUnfocus).attr("class", "noHighlight");
                    divParentIdUnfocus = null;
                }

                $("#" + divParentIdFocus).attr("class", "highlight");
            }
        </script>
        <style type="text/css">
            .highlight{
                background-color:blue;
                border: 3px solid black;
                font-weight:bold;
                color: white;
            }
            .noHighlight{           
            }
            div, h1,textarea, select { outline: none; }

        </style>
    <head>
    <body>
        <div id = "div1" tabindex="100">
            <h1>Div 1</h1> <br />
            <textarea rows="2" cols="25" tabindex="101">~Your Text Here~</textarea> <br />
            <textarea rows="2" cols="25" tabindex="102">~Your Text Here~</textarea> <br />
            <textarea rows="2" cols="25" tabindex="103">~Your Text Here~</textarea> <br />
            <textarea rows="2" cols="25" tabindex="104">~Your Text Here~</textarea> <br />
        </div>
        <div id = "div2" tabindex="200">
            <h1>Div 2</h1> <br />
            <textarea rows="2" cols="25" tabindex="201">~Your Text Here~</textarea> <br />
            <textarea rows="2" cols="25" tabindex="202">~Your Text Here~</textarea> <br />
            <textarea rows="2" cols="25" tabindex="203">~Your Text Here~</textarea> <br />
            <textarea rows="2" cols="25" tabindex="204">~Your Text Here~</textarea> <br />
        </div>
        <div id = "div3" tabindex="300">
            <h1>Div 3</h1> <br />
            <textarea rows="2" cols="25" tabindex="301">~Your Text Here~</textarea> <br />
            <textarea rows="2" cols="25" tabindex="302">~Your Text Here~</textarea> <br />
            <textarea rows="2" cols="25" tabindex="303">~Your Text Here~</textarea> <br />
            <textarea rows="2" cols="25" tabindex="304">~Your Text Here~</textarea> <br />
        </div>
        <div id = "div4" tabindex="400">
            <h1>Div 4</h1> <br />
            <textarea rows="2" cols="25" tabindex="401">~Your Text Here~</textarea> <br />
            <textarea rows="2" cols="25" tabindex="402">~Your Text Here~</textarea> <br />
            <textarea rows="2" cols="25" tabindex="403">~Your Text Here~</textarea> <br />
            <textarea rows="2" cols="25" tabindex="404">~Your Text Here~</textarea> <br />
        </div>      
    </body>
</html>

사양 :

:focus요소에 포커스가 (키보드 이벤트 또는 텍스트 입력의 다른 형태를 수용) 동안 의사 클래스에 적용됩니다.

<div>입력을 허용하지 않으므로 :focus. 또한 CSS는 하위 요소를 대상으로하는 요소에 스타일을 설정할 수 없습니다. 따라서 JavaScript를 사용하지 않는 한 실제로이 작업을 수행 할 수 없습니다.


As far as I am aware you have to use javascript to travel up the dom.

Something like this:

$("textarea:focus").parent().attr("border", "thin solid black");

you'll need the jQuery libraries loaded as well.

ReferenceURL : https://stackoverflow.com/questions/7876283/using-focus-to-style-outer-div

반응형