简体   繁体   English

当在另一个类中添加一个类时,在容器类上添加CSS,反之亦然

[英]Add CSS on a container class when a class is added inside another class and vice versa

This is a HTML example of my website. 这是我的网站的HTML示例。 I want to change CSS when some class is added on a container with an img in it. 当某个类添加到带有img的容器中时,我想更改CSS。 In this situation, a class is been added onclick to the img. 在这种情况下,将onclick类添加到img。 How can I add CSS when a class is added and a class is removed. 添加类并删除类时,如何添加CSS。 See the examples below. 请参阅下面的示例。 I see some tutorials with javascript but can this also been done with just CSS? 我看到了一些使用javascript的教程,但是也可以仅使用CSS来完成吗?

 .container //when image is unselected{ border: 2px dotted; } .container //when image is selected{ border: 2px solid; } 
 //When image is unselected <div class="container"> <div class="checkbox"> <div class="value"> <img class="some-image"> </div> </div> </div> //When image is selected <div class="container"> <div class="checkbox"> <div class="value"> <img class="some-image selected"> </div> </div> </div> 

Yes, this is possible using only CSS. 是的,仅使用CSS即可实现。 The key here is to use the contenteditable global attribute and :target pseudo class , as demonstrated below. 此处的关键是使用contenteditable全局属性:target伪类 ,如下所示。

 .container { display: inline-block; } .container:focus { outline: none; } .container:focus img { border: 2px dotted; } .container img { border: 2px solid; } 
 <div> <div class="container" contenteditable> <div class="checkbox"> <div class="value"> <img class="some-image" src="https://via.placeholder.com/100x100"> </div> </div> </div> <div class="container" contenteditable> <div class="checkbox"> <div class="value"> <img class="some-image" src="https://via.placeholder.com/100x100"> </div> </div> </div> </div> 

This is a something that is very simple to accomplish in JavaScript. 在JavaScript中,这很容易完成。 JS allows you to write a lot of event driven code. JS允许您编写许多事件驱动的代码。 Here is an example of what you are trying to do in JS. 这是您尝试在JS中执行的示例。

Link 链接

If you are looking for a pure css solution the closest thing you will get is this: 如果您正在寻找纯CSS解决方案,那么您将得到的最接近的结果是:

.container {
  border: 2px dotted;
}

.container:active {
  border: 2px solid;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM