CSS 使用 :focus 来设置外部 div 的样式?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7876283/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 01:59:13  来源:igfitidea点击:

Using :focus to style outer div?

cssfocusstylesheet

提问by Weblurk

When I begin writing text in the textarea, I want the outer div, with a class box, to have it's border turned solid instead of dashed, but somehow the :focus doesn't apply in this case. If it works with :active, how come it doesn't work with :focus?

当我开始在 textarea 中编写文本时,我希望带有类框的外部 div 的边框变成实线而不是虚线,但不知何故 :focus 在这种情况下不适用。如果它与 :active 一起工作,为什么它不能与 :focus 一起工作?

Any ideas why?

任何想法为什么?

(Note. I want the DIV's border to turn solid, NOT the textareas)

(注意。我希望 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>

采纳答案by David says reinstate Monica

While this can't be achieved with CSS/HTML alone, it can be achieved with JavaScript (without need of a library):

虽然这不能单独使用 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 demo.

JS小提琴演示

Incidentally, with a library, such as jQuery, the above could be condensed down to:

顺便说一句,对于一个库,比如 jQuery,上面的内容可以浓缩为:

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

JS Fiddle demo.

JS小提琴演示

References:

参考:

回答by Karlen Kishmiryan

DIVelements can get focus if set the tabindexattribute. Here is the working example.

DIV如果设置tabindex属性,元素可以获得焦点。这是工作示例。

#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>

For more information about focusand blur, you can check out this article.

有关详细信息focus,并blur,你可以看看这篇文章

Update:And here is another example using focusto create a menu.

更新:这是另一个focus用于创建menu.

#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>

回答by Danield

Other posters have already explained why the :focuspseudo class is insufficient, but finally there is a CSS-based standard solution.

其他发帖人已经解释了:focus伪类不足的原因,但最后还是有一个基于CSS的标准解决方案。

CSS Selectors Level 4 defines a new pseudo class:

CSS Selectors Level 4 定义了一个新的伪类:

:focus-within

:焦点内

From MDN:

来自MDN

The :focus-withinCSS pseudo-class matches any element that the :focuspseudo-class matches or that has a descendant that the :focuspseudo-class matches. (This includes descendants in shadow trees.)

:focus-withinCSS伪类的任何元素相匹配:focus伪类比赛或具有后代的:focus伪类比赛。(这包括影子树中的后代。)

So now with the :focus-withinpseudo class - styling the outer div when the textareagets clicked becomes trivial.

所以现在使用: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 demo

代码笔演示

NB:Browser Support: Chrome (60+), Firefox and Safari

注意:浏览器支持:Chrome (60+)、Firefox 和 Safari

回答by Tekill

This can now be achieve through the css method :focus-withinas examplified in this post: http://www.scottohara.me/blog/2017/05/14/focus-within.html

这现在可以通过 css 方法来实现,:focus-within如本文所示:http: //www.scotohara.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>

回答by Matthew Egan

Simple use JQuery.

简单使用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>

回答by Thomas Vanderhoof

You can tab between div tags. Just add a tab index to the div. It's best to use jQuery and CSS classes to solve this problem. Here's a working sample tested in IE, Firefox, and Chrome (Latest versions... didn't test older).

您可以在 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>

回答by Jon

As per the spec:

根据规范

The :focuspseudo-class applies while an element has the focus (accepts keyboard events or other forms of text input).

:focus伪类适用而一个元件具有焦点(接受键盘事件或其它形式的文本输入的)。

The <div>does not accept input, so it cannot have :focus. Furthermore, CSS does not allow you to set styles on an element based on targeting its descendants. So you can't really do this unless you are willing to use JavaScript.

<div>不接受输入,所以它不能有:focus。此外,CSS 不允许您基于定位其后代的元素在元素上设置样式。因此,除非您愿意使用 JavaScript,否则您无法真正做到这一点。

回答by CBRRacer

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

据我所知,您必须使用 javascript 来访问 dom。

Something like this:

像这样的东西:

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

you'll need the jQuery libraries loaded as well.

您还需要加载 jQuery 库。

回答by kintsukuroi

Some people, like me, will benefit from using the :focus-withinpseudo-class.

有些人,比如我,会从使用:focus-within伪类中受益。

Using it will apply the css you want to a div, for instance.

例如,使用它会将您想要的 css 应用到 div。

You can read more here https://developer.mozilla.org/en-US/docs/Web/CSS/:focus-within

你可以在这里阅读更多https://developer.mozilla.org/en-US/docs/Web/CSS/:focus-within