简体   繁体   English

Onclick 更改 Class 样式值而不更改 Class 名称

[英]Onclick Change the Class Style Value without changing Class name

I need to change a value of a Class Style Property Color from RED to GREEN on click.我需要在单击时将 Class 样式属性颜色的值从红色更改为绿色。

<style>
.c1
{
color : RED;
}

</style>

<a id="a1" class="c1" onclick="changeclassstyle()">
Hi
</a>

<script>
function changeclassstyle()
{
/* here i need to change the style of class c1 */
}
</script>

I need to change the color of c1 class to GREEN.我需要将 c1 class 的颜色更改为绿色。

Note: I dont want it to be done with "ID" & I dont want to create new Class and change the class name.注意:我不想“ID”来完成,我不想创建的 Class 并更改 class 名称。 I want it to happen with same class name.我希望它以相同的 class 名称发生。

 function changeclassstyle() { var c = document.getElementsByClassName("c1"); for (var i=0; i<c.length; i++) { c[i].style.color = "green"; } } 
 .c1 { color : RED; } 
 <a id="a1" class="c1" onclick="changeclassstyle()"> Hi </a> 

<a id="a1" class="c1" onclick="changeclassstyle(this);">
Hi
</a>


<script>

function changeclassstyle(obj)
{
obj.style.color='green';
}
</script>

jQuery version jQuery版本

 function changeToGreen(elem) { $("." + elem.className).css("color", "green"); } 
 .c1 { color: RED; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script> <a id="a1" class="c1" onclick="changeToGreen(this)"> Hi </a> <br/> <p class="c1"> Test </p> 

if you don't want to add javascript to the tag itself you can do it this way: 如果您不想将JavaScript添加到代码本身,则可以通过以下方式进行操作:

var c= document.getElementsByClassName("someClass");


       for (var i = 0; i < c.length; i++)  {
            c[i].onclick=function(){       //on click here instead of on tag

                this.style.color="green";
            }
        }

https://developer.mozilla.org/es/docs/Web/CSS/:active https://developer.mozilla.org/es/docs/Web/CSS/:active

seudoclass:active伪类:活动

.class-label {  
    display: flex;
    width: 100px;
    height: 60px;
    background-color:rgb(201, 201, 201) ; 
    padding: 10px;
    box-sizing: border-box;
    margin: 10px;
    border: 1px solid;
    border-radius: 5px;
    align-items: center;
    justify-content: center;
    font-family: monospace;  
}

.class-label:active {
    background-color: salmon;
    color: white;
}

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

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