使用:focus to style outer div? [英] Using :focus to style outer div?

查看:126
本文介绍了使用:focus to style outer div?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我开始在textarea中编写文本时,我想要外部div,用一个类框,让它的边框变成固体而不是虚线,但不知何故:焦点不适用于这种情况。

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?

任何想法为什么?

(注意,我希望DIV的边框变为实体,而不是textareas)

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

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(不需要库)来实现:

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

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

顺便说一句,使用一个库,比如jQuery,可以缩减为:

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

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

JS Fiddle demo

参考资料:

  • getElementsByTagName().
  • onfocus.
  • onblur.
  • parentNode.
  • tagName.
  • toString().
  • toLowerCase().
  • style.
  • focus().
  • blur().
  • parent().
  • css().

这篇关于使用:focus to style outer div?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆