单击时更改元素的颜色

Change colour of an element when clicked

本文关键字:颜色 元素 单击      更新时间:2023-10-16

当单击"center"容器或"right"容器时(再次单击后返回其状态),我不知道如何更改菜单元素的颜色。目前,我菜单中的3行是白色的,我想在单击这些"center"answers"right"容器时将它们更改为红色。

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用于菜单元素:

.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;
}

为您想要的颜色定义新的类,例如

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

然后使用jQuery:切换它们

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

注意:如果你使用CSS指定原始颜色,那么你就不需要!重要的

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

添加onClick()方法

Html:

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

并在<script>标签中添加此功能:

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