【问题标题】:Focus does not work对焦不起作用
【发布时间】:2016-12-25 05:49:14
【问题描述】:
我有以下代码:JSBin。
我希望这两个 flex-box 最初以灰色作为背景,一旦我们单击一个框,它的整个背景就会变为白色。 .flex-box .col textarea:focus 按预期工作,而 .flex-box .col:focus 不起作用:文本的背景颜色(例如,html、css)始终为灰色。
有谁知道怎么回事?
.flex-box {
display: flex;
width: 100%;
margin: 0;
height: 300px;
}
.flex-box .col {
border: 1px solid green;
flex: 1;
overflow-y: auto;
overflow-x: hide;
background: #F7F7F7;
}
.flex-box .col textarea {
position: relative;
width: 100%;
height: 100%;
resize: none;
border: 0;
font-family: monospace;
background: #F7F7F7;
}
.flex-box .col:focus {
background: white;
}
.flex-box .col textarea:focus {
outline: none;
background: white;
}
<div class="flex-box">
<div class="col" id="html-panel">
<h2>html</h2>
<textarea name="html"></textarea>
</div>
<div class="col" id="css-panel">
<h2>css</h2>
<textarea name="css"></textarea>
</div>
</div>
编辑 1:
实际上,一旦我们点击一个框的文本区域,我希望它的标题的背景也系统地变成白色。用 JavaScript 设置事件监听器让我很恼火(因为我已经有几个事件监听器了)。难道没有办法单独使用 CSS 来实现吗?
【问题讨论】:
标签:
html
css
flexbox
pseudo-element
【解决方案1】:
这是因为textarea 得到:focus 而不是div。单独使用 CSS 实现结果的一种方法是为背景添加额外的 div,并在 textarea 聚焦时使用兄弟选择器。
.flex-box {
display: flex;
width: 100%;
margin: 0;
height: 300px;
}
.flex-box .col {
border: 1px solid green;
flex: 1;
overflow-y: auto;
overflow-x: hide;
background: #F7F7F7;
Position: relative;
}
.flex-box .col textarea {
position: relative;
width: 100%;
height: 100%;
resize: none;
border: 0;
font-family: monospace;
background: #F7F7F7;
Z-index: 1;
}
.flex-box .col label {
display: block;
font-size: 2em;
font-weight: bold;
padding: 10px;
position: relative;
Z-index: 1;
}
.flex-box .col:focus {
background: white;
}
.flex-box .col textarea:focus {
outline: none;
background: white;
}
.flex-box .col .background {
Position: absolute;
Top: 0;
Left: 0;
Right: 0;
Bottom: 0;
Height: 100%;
Width: 100%;
Z-index: 0;
}
.flex-box .col textarea:focus ~ .background {
background: white;
}
<div class="flex-box">
<div class="col" id="html-panel">
<label for="html">html</label>
<textarea id="html" name="html"></textarea>
<div class="background"></div>
</div>
<div class="col" id="css-panel">
<label for="css">css</label>
<textarea id="css" name="css"></textarea>
<div class="background"></div>
</div>
</div>
【讨论】:
-
-
感谢您的想法...我正在构建this:一旦我们点击标题,我希望它的 col(包括它的 textarea)也变成白色(抱歉,在开始)。我还在调试这个...
-
很好...我也调试了the mine,但我认为使用label肯定更好...