【问题标题】:Add a class to a span with a particular text [duplicate]将类添加到具有特定文本的跨度 [重复]
【发布时间】:2022-01-13 10:22:39
【问题描述】:

我最初的问题是我想在主菜单标题上添加自定义颜色。 我已经通过在 CSS 中使用 title + 属性来做到这一点。 但是我不希望在悬停时出现标题属性。 所以我有了另一个想法,想知道是否可以在特定文本中添加一个类(使用 JS)?如果是的话怎么做?

每个菜单标题具有以下结构: <span class="menu-text">Random text</span>

它们都有“菜单文本”类,这就是我试图区分它们的原因。为了应用不同的颜色。

提前感谢您的回答!

【问题讨论】:

    标签: javascript css menu


    【解决方案1】:

    这说明了一种在单击元素时向元素添加类的简单方法。

    window.addEventListener("load", function(){
        // gets the elements with the classname .menu-text in a nodeList
        const getAllElements = document.querySelectorAll('.menu-text');
        
        for (let item of getAllElements) {
          // iterates over all of them, and attaches an event
          item.addEventListener('click', function () {
            // adds the class .has-background-red
            this.classList.add('has-background-red');
          });
        }
    });
    .container {
      /* just for visual purposes */
      display: flex;
      gap: 16px;
    }
    
    .has-background-red {
      background-color: red;
    }
    <div class="container">
      <span class="menu-text">Random text</span>
      <span class="menu-text">Random text</span>
      <span class="menu-text">Random text</span>
      <span class="menu-text">Random text</span>
      <span class="menu-text">Random text</span>
      <span class="menu-text">Random text</span>
      <span class="menu-text">Random text</span>
      <span class="menu-text">Random text</span>
      <span class="menu-text">Random text</span>
    </div>

    【讨论】:

    • 点击不是问题。 文本内容是添加类的标准。我建议你重新阅读这个问题。
    • 是的,确实,标准是“随机文本”。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-16
    • 2012-01-21
    • 1970-01-01
    • 1970-01-01
    • 2021-09-14
    • 1970-01-01
    • 2016-01-18
    相关资源
    最近更新 更多