首页 > 解决方案 > not(:focus):before 在单击某些占位符文本后取消对可编辑 div 的关注

问题描述

我想在属性映射上插入可编辑的 div 和占位符文本时遇到了一些问题。content:attr(data-text)如果您查看示例,可以在任何地方单击第一行,并且可以立即进行书写。对于其他的,仅当您不单击占位符文本时才可以编写文本。单击占位符文本有一些机会起作用,但大多数情况下,直到用户再次单击它才会获得焦点。

我打破了这一点,并发not(:focus)现在 css 中造成了麻烦。我认为它正是为了这种交互,但似乎 dom 操作是罪魁祸首。将其保留将占位符留在 div 上,但单击有效。user-select: none;似乎对此没有任何影响。

如何防止 div 元素在使用时立即失去点击焦点not(:focus)

    [contentEditable=true]:empty:not(:focus):before{
    content:attr(data-text);
    cursor: text;
    color: red;
    }

    .edit {
    border: 2px dotted black;
    background-color: #CCC;
    min-width: 100px;
    padding:10px;
    margin:10px;
    }
    <div class='edit' contentEditable=true data-text='Some text missing #####'>Working one</div>
    <div class='edit' contentEditable=true data-text='Some text missing #####'></div>
    <div class='edit' contentEditable=true data-text='Some text missing #####'></div>
    <div class='edit' contentEditable=true data-text='Some text missing #####'></div>
    <div class='edit' contentEditable=true data-text='Some text missing #####'></div>

标签: htmlcssdom

解决方案


pointer-events:none;似乎解决了奇怪的问题。可能是因为它阻止了伪元素捕获使文本区域失去焦点的单击事件。

[contentEditable=true]:empty:not(:focus):before {
  content: attr(data-text);
  cursor: text;
  color: red;
  pointer-events:none;
}

.edit {
  border: 2px dotted black;
  background-color: #CCC;
  min-width: 100px;
  padding: 10px;
  margin: 10px;
}
<div class='edit' contentEditable=true data-text='Some text missing #####'>Working one</div>
<div class='edit' contentEditable=true data-text='Some text missing #####'></div>
<div class='edit' contentEditable=true data-text='Some text missing #####'></div>
<div class='edit' contentEditable=true data-text='Some text missing #####'></div>
<div class='edit' contentEditable=true data-text='Some text missing #####'></div>


推荐阅读