[英]Change style of another element when contenteditable has focus
I want to change the style of another element when a contenteditable div has focus as shown below: 当一个contenteditable div具有焦点时,我想改变另一个元素的样式,如下所示:
[contenteditable="true"]:focus .testClass { background-color: black; }
<div contenteditable="true">Hello World</div> <button class="testClass">Test</button>
Unfortunately the above isn't working, I have tried the following CSS also: 不幸的是上面没有用,我也尝试过以下CSS:
[contenteditable="true"]:focus + .testClass {
[contenteditable="true"]:focus > .testClass {
[contenteditable="true"]:focus, .testClass {
Using [contenteditable="true"]:focus
on its own works fine to style the editable div when focus is applied, but none of these work to style another element at the same time. 使用
[contenteditable="true"]:focus
于自己的工作,可以在应用焦点时设置可编辑div的样式,但这些都不能同时设置另一个元素的样式。 Is this possible to do? 这可能吗?
Is this what you want: 这是你想要的吗:
[contenteditable="true"]:focus { background-color: black; }
<div contenteditable="true">Hello World</div> <button class="testClass">Test</button>
Or this (you mentioned you've tried it, but it does work): 或者这(你提到过你已经尝试过,但它确实有效):
[contenteditable="true"]:focus + .testClass { background-color: black; }
<div contenteditable="true">Hello World</div> <button class="testClass">Test</button>
Here some reading on CSS selectors: https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Getting_started/Selectors 这里有一些关于CSS选择器的阅读: https : //developer.mozilla.org/en-US/docs/Web/Guide/CSS/Getting_started/Selectors
You need to use ~
. 你需要用
~
。 It's the general sibling selector which separates two selectors and matches the second element only if it is preceded by the first, and both share a common parent. 它是一般的兄弟选择器,它分隔两个选择器,只有当它在第一个元素之前时才匹配第二个元素,并且它们共享一个共同的父元素。 Check this:
检查一下:
[contenteditable="true"]:focus ~ .testClass {
background: red;
}
[contenteditable="true"]:focus ~ .testClass { background: red; }
<div contenteditable="true">Hello World</div> <button class="testClass">Test</button>
More about the general sibling selector can be read over here . 有关一般兄弟选择器的更多信息,请参阅此处 。
[contenteditable="true"]:focus ~ .testClass will do the job as Fahad Hasan said [contenteditable =“true”]:焦点〜.testClass将像Fahad Hasan所说的那样完成工作
The ~ symbol means the first element right after ( not child ) 〜符号表示紧随其后的第一个元素(不是子元素)
you can change the style of .textClass when your div has focus, by using jquery: 你可以通过使用jquery在你的div具有焦点时改变.textClass的样式:
$("div[contenteditable=true]").focusin(function () {
$(".testClass").css({
"background-color": "black",
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.