繁体   English   中英

单击时更改元素背景颜色

[英]Changing the element background color on click

我在下面附上了我的 HTML 代码。 我正在尝试在单击时更改此元素的颜色。 我有一个可以点击的脚本,但由于某种原因颜色没有改变。

 function myfunction() { var elements = document.getElementsByClassName("tag14"); // get all elements for(var i = 0; i < elements.length; i++){ elements[i].style.backgroundColor = "blue"; } }
 .tag14 span { padding: 6px 10px; background: #D0E8E4; border-radius: 20px; color: #091747; font-family: Roboto; font-size: 14px; margin: 0 4px 8px 0; font-weight: 500; display: inline-block; word-wrap: break-word; white-space: normal; }.tag14 span:hover{ background:red; }.tag14 span:focus{ background:green; }
 <div class="tag14" onclick="myfunction();"><span>Hello</span></div>

我认为这是 function 中运行不正常的东西。

更新 2在帮助下,我想出了如何打开和关闭点击:

<style>
.tag14 span {
    padding: 6px 10px;
    background: brown;
    border-radius: 20px;
    color: #091747;
    font-family: Roboto;
    font-size: 14px;
    margin: 0 4px 8px 0;
    font-weight: 500;
    display: inline-block;
    word-wrap: break-word;
    white-space: normal;
}


.tag14 span:focus{
   background:green;
}

</style>

<script>
function myfunction() {
    
    var elements = document.getElementsByClassName("tag_span"); // get all elements
    
      for(var i = 0; i < elements.length; i++){
            if (elements[i].style.backgroundColor === ""){
                elements[i].style.backgroundColor = "blue";
                elements[i].style.color = "white"; 
            } else {
                elements[i].style.backgroundColor = "";
                elements[i].style.color = "black";
            }
      }
}
</script>


<div class="tag14" onclick="myfunction();"><span class="tag_span">Hello</span></div>

因此,您只需要 select 跨度元素而不是 DIV 元素。

所以在这里我为跨度添加了一个额外的 class ,您可以使用 select 跨度本身。

 function myfunction() { var elements = document.getElementsByClassName("tag_span"); // get all elements for(var i = 0; i < elements.length; i++){ elements[i].style.backgroundColor = "blue"; elements[i].style.color = "white"; //added this extra element so that you can see the Hello } }
 .tag14 span { padding: 6px 10px; background: #D0E8E4; border-radius: 20px; color: #091747; font-family: Roboto; font-size: 14px; margin: 0 4px 8px 0; font-weight: 500; display: inline-block; word-wrap: break-word; white-space: normal; }.tag14 span:hover{ background:red; /* you can add red.important so it will still work after the click event, So when you change the Span background color in JS. it will be an inline css styling that has higher priority than this one*/ }:tag14 span:focus{ background;green; }
 <div class="tag14" onclick="myfunction();"><span class="tag_span">Hello</span></div>

但我不建议您将 onclick function 放在 Div 元素上。 所以最好通过添加一个事件监听器把它放在脚本上。 您可以在此处了解有关事件侦听器的更多信息w3schools

暂无
暂无

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

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