【问题标题】:Change the background of an active icon on a menu in JavaScript [duplicate]在JavaScript中更改菜单上活动图标的背景[重复]
【发布时间】:2020-11-30 16:07:02
【问题描述】:

我正在尝试使蓝色背景颜色保持在活动的 SVG 图标上,该图标使用纯 JavaScript 显示文本。我还从语义 UI 中获取图标。

这是当前菜单列表的代码,到目前为止,clg 将 for 中的项目打印给我:

HTML

<span class="menu-bar">
  <a href="javascript:void(0)" class="itemList"> <svg><svg/> </a>
  <a href="javascript:void(0)" class="itemList"> <svg><svg/> </a>
  <a href="javascript:void(0)" class="itemList"> <svg><svg/> </a>
  <a href="javascript:void(0)" class="itemList"> <svg><svg/> </a>
  <i class="angle left icon iconColor tooltip" id="angle_icon"></i>
  <i class="text height icon iconColor tooltip" id="measure_icon"></i>
</span>

CSS

.menu-bar {
   display: block;
   width: 100%;
   height: 100%;
   margin-top: -10px;
}

.menu-bar svg {
    display: inline-block;
    width: 1em;
    padding: 0.3em;
    border-radius: 4px;
    margin-right: 20px;
}

.menu-bar a.toggle-state  {
   background-color: #1A41B5;
}

JavaScript 代码(目前为止)

function changeIndex(){
    for (let i = 0; i <= items.length; i++) {
        console.log(items[i])
    }
}

我设法修复它:

function _clearIcon() {
    for (const icon of items) {
        if(icon.classList.contains('menu-barActive')) {
            icon.classList.remove('menu-barActive')
        }
    }
}

function changeIndex() {
    for (const icon of items) {
        icon.onclick=()=> {
            _clearIcon()
            let activeId = document.getElementById(icon.id)
            activeId.classList.add('menu-barActive')
        }
    }

【问题讨论】:

    标签: javascript html css svg


    【解决方案1】:

    在现代浏览器中,您可以使用Custom Elements 创建自己的 HTML 标记。

    定义您的自定义元素&lt;icon-toolbar&gt;&lt;svg-icon&gt; 一次

    你写的是:

        <icon-toolbar>
          <svg-icon is="icon1"></svg-icon>
          <svg-icon is="icon2"></svg-icon>
          <svg-icon is="icon3"></svg-icon>
          <svg-icon is="icon4"></svg-icon>
        </icon-toolbar>
    

    下面的代码片段。

    JSFiddle 在:https://jsfiddle.net/CustomElementsExamples/yx27sh08/

    customElements.define("icon-toolbar", class extends HTMLElement {
        connectedCallback() {
          this.icons = [...this.querySelectorAll("svg-icon")];
          this.addEventListener("click", (evt) => {
            const select = (icon, selected = true) => {
              if (selected) icon.setAttribute("selected", "selected");
              else icon.removeAttribute("selected");
            }
            const clickedicon = evt.target.closest("svg-icon");
            if (evt.ctrlKey) select(clickedicon, !clickedicon.hasAttribute("selected"));
            else {
              this.icons.map(icon => icon.hasAttribute("selected") && select(icon, false));
              select(clickedicon);
            }
          });
        }
      })
      customElements.define("svg-icon", class extends HTMLElement {
        connectedCallback() {
          const path = {
            icon1: "M80 35a5 5 0 01-5-6V17a7 7 0 00-7-6H56a5 5 0 010-11h12a17 17 0 0118 17v12a5 5 0 01-6 6zM5 35a5 5 0 01-5-6V17A17 17 0 0117 0h12a5 5 0 010 11H17a7 7 0 00-6 6v12a5 5 0 01-6 6z",
            icon2: "M43 86a5 5 0 01-6-6V5a5 5 0 0111 0v75a5 5 0 01-5 6zm37-38H5a5 5 0 010-11h75a5 5 0 110 11zM43 86a5 5 0 01-4-2L28 73a5 5 0 014-9h22a5 5 0 014 9L47 84a5 5 0 01-4 2zm11-64H32a5 5 0 01-4-9L39 2a5 5 0 014-2 5 5 0 014 2l11 11a5 5 0 01-4 9z",
            icon3: "M5 43a38 38 0 0038 38V5A38 38 0 005 43z",
            icon4: "M86 86H5a5 5 0 110-11h81a5 5 0 110 11zm-25 0H27a5 5 0 01-3-2L6 66a19 19 0 010-27l17-17a5 5 0 017 0l45 45a5 5 0 010 7L65 84a5 5 0 01-4 2zM30 75h29l5-5-37-37-14 14a8 8 0 000 12z",
          } [this.getAttribute("is")];
          this.innerHTML = `<svg viewBox='0 0 85 85'><path d='${path}'/></svg>`
        }
      })
    icon-toolbar {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(20px, 1fr));
        grid-gap: 5px;
      }
      svg-icon {
        cursor: pointer;
        background: black;
        fill: #b8b8b8;
      }
      svg-icon:hover {
        background:lightgreen;
        fill:black;
      }
      svg-icon[selected] {
        background: green;
        fill: gold;
      }
      svg-icon[selected]:hover {
        background: lightcoral;
        fill: grey;
      }
    Select multiple with Control Key
    <icon-toolbar>
      <svg-icon is="icon1"></svg-icon>
      <svg-icon is="icon2"></svg-icon>
      <svg-icon is="icon3"></svg-icon>
      <svg-icon is="icon4"></svg-icon>
    </icon-toolbar>

    更高级的&lt;svg-icon&gt;https://IconMeister.github.io

    在 Angular、Vue 或 Svelte 中应该可以正常工作。对于 React,你必须跳过一些障碍...... 因为只有 71% 的 React 支持这个现代 W3C 标准 (https://custom-elements-everywhere.com/)

    【讨论】:

      【解决方案2】:

      而不是:

      items[i].style["1a41b5"] = color;
      

      你应该输入:

      items[i].style.color = "#1a41b5";
      

      因为colorstyle 属性的内置对象。我认为您可能将style 混淆为方法而不是属性。方法包括括号和参数,例如.getElementById("parameter")。您可以将方法视为对对象执行操作的函数。例如在...

      var x = document.getElementById("some-id");

      ...getElementById() 正在积极获取 id 为 some-id 的元素。但是,将属性视为变量的扩展:您必须为其分配一个值。所以添加到我们之前的例子......

      x.innerHTML = "&lt;p&gt;Hello World&lt;/p&gt;";

      如您所见,您必须为属性赋值。在这种情况下,上面的代码将&lt;p&gt;Hello World&lt;/p&gt;分配给id为some-id的元素的内部HTML(因为我们为x分配了id为some-id的元素的值)。在这种情况下,这是在屏幕上显示“Hello World”。

      所以请记住,.style 和 .color 都是 属性,它们需要设置值,这与可用于对变量/对象执行操作的方法不同。

      希望这会有所帮助。快乐编码! :)

      【讨论】:

      • 是的,我刚刚检查它是错误的,现在我试图在 for 元素下添加一个 eventListener 以检查它现在是否可以更改单击图标的 bg 颜色,还修复了一些 css 和我犯的html错误,让我们看看它现在是否有效
      • 太棒了!我也很乐意接受其他代码,但我不太擅长 web 开发,所以我会尽力而为:P
      • 哈哈哈我还在努力!我还是个初学者需要时间
      • 没问题,我知道那是什么感觉 :)。告诉我代码是否运行良好,希望看到最终产品。如果没有,请随时评论您希望我看的任何内容。但不要感到匆忙或有义务:)
      • 点击时我设法改变了背景颜色,但现在我必须存储 i 的值,所以当我点击其他图标时,我将它的颜色更改为 #171717 和新的活动更改为蓝色,而不是全部蓝色
      【解决方案3】:

      我在可缩放矢量图形 (svg) 方面不太擅长。但是,它清楚地表明您忘记正确结束 svg 标记...

      看起来像

      <svg></svg>
      

      并且应该有一个&lt;svg&gt;的跟踪标签。那可以是&lt;rect /&gt; 标签

      例如

      <svg width="20" height="20"> <rect width="20" height="20" /> </svg>
      

      重要的是您需要使用fill 属性在svg 图标中应用背景颜色。

      您可以在https://www.w3schools.com/graphics/svg_rect.asp 中看到更多关于 svg 的示例和教程。

      我已尝试修改您的代码并制作了类似于以下代码的内容...我认为这就是您想要的。

      在以下代码中,addEventListener 用于在菜单栏中传递单击事件的任何位置调用。而children属性用于返回特定节点或标签的子元素。

      查看以下代码:

      <!DOCTYPE html>
      <html>
      <head>
          <title>HTML/jQuery</title>
          <style type="text/css">
              menu-bar {
        display: block;
        
        margin-top: -10px;
      }
      
      .menu-bar svg {
        display: inline-block;
      
      }
      .menu-bar a.toggle-state  {
        background-color: #1a41b5;
      }
          </style>
      </head>
      <body>
      
      
      <span class="menu-bar">
          <a href="javascript:void(0)" class="itemList"><svg width="20" height="20"><rect width="20" height="20" style="fill:rgb(0,0,255)" /></svg></a>
          <a href="javascript:void(0)" class="itemList"><svg width="20" height="20"><rect width="20" height="20" style="fill:rgb(0,0,255)" /></svg></a>
          <a href="javascript:void(0)" class="itemList"><svg width="20" height="20"><rect width="20" height="20" style="fill:rgb(0,0,255)" /></svg></a>
          <a href="javascript:void(0)" class="itemList"><svg width="20" height="20"><rect width="20" height="20" style="fill:rgb(0,0,255)" /></svg></a>
          <a href="javascript:void(0)" class="itemList"><svg width="20" height="20"><rect width="20" height="20" style="fill:rgb(0,0,255)" /></svg></a>
         <i class="angle left icon iconColor tooltip" id="angle_icon"></i>
         <i class="text height icon iconColor tooltip" id="measure_icon"></i>
      </span>
      
      <script type="text/javascript">
      
          (function(){
              
              var c = document.getElementsByClassName('itemList');
              
              for (var i = 0; i < c.length; i++) {
                  
      
                  c[i].addEventListener('click',function(){
      
                      this.children[0].children[0].style.fill = "red";
                      
                  })
                  
              }
      
          })();
          
      </script>
      </body>
      </html>
      

      【讨论】:

      • 我故意删除了 svg 链接,我尝试 rn 的目的是在我点击其他元素时为 i 值存储它之前的值
      • 对了,你要存储什么值...请给出具体的名称,例如背景色、文本等。
      • 我要存储一个for循环的索引号
      • jsfiddle.net/hLj7t1pq 好了,希望能更好理解
      • jsfiddle.net/rakeysharyal/b70zh8dj/72我希望这是你想要的……但我不知道我是否成功地理解了你。
      猜你喜欢
      • 2011-02-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多