简体   繁体   English

单击时更改元素的颜色

[英]Change colour of an element when clicked

I cannot figure out how to change the colour of my menu elements when the " center " container or the " right " container is clicked (returning its state once clicked on again). 当单击“ center ”容器或“ right ”容器时(再次单击返回其状态),我无法弄清楚如何更改菜单元素的颜色。 Currently my 3 lines that are within my menu are white, I want to change them to red when these " center " and " right " containers are clicked. 当前,我菜单中的3行是白色的,当我单击这些“ center ”和“ right ”容器时,我想将它们更改为红色。

HTML for menu and containers: 菜单和容器的HTML

<div class="menu">
    <div class="line"></div>
    <div class= "container" id= "center">
        <h1 style="color:white"><a>LOREM IPSUM<a/></h1>
    </div>
    <div class="container" id= "right">
        <h1 style="color:white"><a>LOREM IPSUM</a></h1>
    </div>

CSS for menu elements: 菜单元素的CSS

.menu .line {
  height: 5px;
  width: 40px;
  background: #fff;
  position: absolute;
  top: 22.5px;
  left: 5px;
  -webkit-transition: all 250ms linear;
  transition: all 250ms linear;
  z-index: 100;
}
.menu .line:after, .menu .line:before {
  content: ' ';
  height: 5px;
  width: 40px;
  background: #fff;
  position: absolute;
  -webkit-transition: all 250ms linear;
  transition: all 250ms linear;
}
.menu .line:before {
  top: -10px;
}
.menu .line:after {
  bottom: -10px;
}

Define new classes for the colors you want, eg 为所需的颜色定义新的类,例如

.red {
    color: red !important;
}
.green {
    color: green !important;
}

Then toggle them using jQuery: 然后使用jQuery切换它们:

$('#center').click(function() {
    $(this).find('h1').toggleClass('red');
});
$('#right').click(function() {
    $(this).find('h1').toggleClass('green');
});

Note: If you assign the original color using CSS then you don't need the !important. 注意:如果使用CSS分配原始颜色,则不需要!important。

我无法理解您的示例html,因此这是使用jQuery的.toggleClass示例演示

Add an onClick() method 添加一个onClick()方法

Html: HTML:

<h1 style="color:white" onclick="changeColor(this);"><a>LOREM IPSUM<a/></h1>

and add this function in the <script> tag: 并在<script>标记中添加此功能:

function changeColor(element){
    element.style.color='red';
}

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

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