【问题标题】:Why doesn't the sibling selector work for contenteditable elements?为什么兄弟选择器不适用于 contenteditable 元素?
【发布时间】:2021-11-22 09:37:24
【问题描述】:

我已经把这支笔放在一起了:https://codepen.io/NanoSpicer/pen/YzQgQVd

这个想法是,当我想要设置样式的元素之前的元素被聚焦时,我想使用兄弟选择器设置某个元素的样式。

它适用于输入元素,但在使用具有contenteditable 属性的元素时会失败:

.container,
form {
  width: 30%;
  display: flex;
  flex-direction: column;
  gap: 10px;
}

div[contenteditable="true"]::before {
  text-color: gray;
  opacity: 0.6;
  content: attr(placeholder);
}

div[contenteditable="true"],
input {
  /* remove system hightlighting*/
  outline-style: none;
  box-shadow: none;
  min-height: 40px;
  appearance: none;
  border: 3px solid;
  border-color: gray;
  border-radius: 6px;
}

div[contenteditable="true"]:focus,
input:focus {
  border-color: blue;
}

*:focus+* {
  border-color: red;
}
<form>
  <input placeholder="first" id="first" type="text">
  <input placeholder="second" id="second" type="password">
</form>
<div class="container">
  <div contenteditable="true" placeholder="first"></div>
  <div contenteditable="true" placeholder="second"></div>
</div>

注意:在 Firefox 和 Chrome 上测试。

【问题讨论】:

    标签: html css css-selectors


    【解决方案1】:

    这很奇怪。可能是一个错误。

    此解决方法适用于 PC 上的 Firefox 和 Chrome。没有测试其他浏览器/平台。

    [contenteditable]:focus + * {
      border-color:green;
    }
    

    【讨论】:

    • 两个答案都明白了:添加属性选择器。两者都赞成,但接受了这个,因为它是第一个出现的,但它们都很好。
    【解决方案2】:

    就像您在 CSS 开头所做的那样,更具体地表明您想要对 contenteditable 属性做出反应。

    默认情况下,div 不可编辑,因此focusable 不可编辑,因此您必须更具体一点。

    要完成这项工作,您应该编辑最后一个 CSS 属性以添加第二个选择器行,就像我在这里写的那样:

    *:focus + *,
    div[contenteditable="true"]:focus + div {
      border-color: red;
    }
    

    或者如果你想让它更通用:

    *:focus + *,
    *[contenteditable="true"]:focus + * {
      border-color: red;
    }
    

    【讨论】:

      猜你喜欢
      • 2018-05-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-13
      • 2015-01-14
      • 2015-07-28
      相关资源
      最近更新 更多