【问题标题】:Font awesome in select menu选择菜单中的字体真棒
【发布时间】:2019-08-30 16:58:04
【问题描述】:

我想在我的选择菜单中添加图标。在 Stack Overflow 的一个页面中,我发现我可以使用 Font Awesome 并将图标作为文本插入。我在头部包含脚本。当我尝试在选择菜单中使用图标时,它不起作用。但它完美地在选择菜单之外工作。是否可以在选择菜单选项中插入图标​​,或者根本不可能?我该怎么做?

有一个字体真棒页面的链接:https://fontawesome.com/cheatsheet/free/solid

有一个我尝试过的sn-p

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <script src="https://kit.fontawesome.com/9593bd7a92.js"></script>
  
</head>
<body>
	<i class="fas fa-truck">Truck</i>
	<br><br><br>
	<select>
		<option><i class="fas fa-truck">Truck</i></option>
	</select>
 
</body>
</html>

【问题讨论】:

    标签: javascript html font-awesome


    【解决方案1】:

    这是 HTML 的限制。 selectoption 元素是 HTML 的原生元素,无法在其中显示 HTML。

    您需要使用 HTML、CSS + JavaScript 模拟 select 元素,然后将值映射到隐藏的 input 元素(如果您将其用作表单的一部分)。

    <ul class="select">
        <li class="option"><i class="fas fa-truck">Truck</i></li>
        <li class="option"><i class="fas fa-star">Star</i></li>
        <li class="option"><i class="fas fa-user">User</i></li>
    </ul>
    

    这有助于深入了解下拉菜单的交互方面(因此它不仅仅显示为列表):https://www.w3schools.com/howto/howto_js_dropdown.asp

    【讨论】:

      【解决方案2】:

      这是我的解决方案

      默认情况下,i 标签会从 HTML 中的选项中去除

      按以下方法添加图标

       <option>&#xf0d1; Truck</option>
      

      还添加以下 CSS

      select,option {
          font-family: 'Arial', 'Font Awesome 5 Pro';
          font-weight: 900;
      }
      

      用您的网站字体名称替换“Arial”字体。

      用你选择的图标代码替换中间代码

      '' + 'f0d1'(fontawsome 卡车图标代码) + ;

      图标代码可以通过右击图标并检查图标i标签的before伪元素找到。

      select,option {
          font-family: 'Arial', 'Font Awesome 5 Pro';
          font-weight: 900;
      }
      <!doctype html>
      <html lang="en">
      
      <head>
        <meta charset="utf-8">
        <script src="https://kit.fontawesome.com/9593bd7a92.js"></script>
      
      </head>
      
      <body>
        <i class="fas fa-truck">Truck</i>
        <br><br><br>
        <select>
          <option>&#xf0d1; Truck</option>
          <option>&#xf0d1; Truck</option>
          <option>&#xf0d1; Truck</option>
          <option>&#xf0d1; Truck</option>
        </select>
      
      </body>
      
      </html>

      更新答案

      由于上述答案不适用于手机,您必须实现自定义选择

      以下是来自 w3schools how to create custom select的代码

      我修改了代码以添加对图标的支持。

      var x, i, j, selElmnt, a, b, c;
      
      
      function generateInnerDiv(index) {
        nametag = document.createElement("span");
        nametag.textContent = selElmnt.options[index].textContent;
        icon = document.createElement("i");
        icon.setAttribute("class", selElmnt.options[index].getAttribute('data-icon'));
        return [icon, nametag]
      }
      
      
      /*look for any elements with the class "custom-select":*/
      x = document.getElementsByClassName("custom-select");
      for (i = 0; i < x.length; i++) {
        selElmnt = x[i].getElementsByTagName("select")[0];
        /*for each element, create a new DIV that will act as the selected item:*/
        a = document.createElement("DIV");
        a.setAttribute("class", "select-selected");
      
      
        innerDiv = generateInnerDiv(selElmnt.selectedIndex)
        a.appendChild(innerDiv[0]);
        a.appendChild(innerDiv[1]);
      
      
        //a.innerHTML = selElmnt.options[selElmnt.selectedIndex].innerHTML;
        x[i].appendChild(a);
        /*for each element, create a new DIV that will contain the option list:*/
        b = document.createElement("DIV"); //items holder
        b.setAttribute("class", "select-items select-hide");
      
      
        for (j = 1; j < selElmnt.length; j++) {
          /*for each option in the original select element,
          create a new DIV that will act as an option item:*/
          c = document.createElement("DIV");
      
          innerDiv = generateInnerDiv(j);
          c.appendChild(innerDiv[0]);
          c.appendChild(innerDiv[1]);
      
          //c.innerHTML = selElmnt.options[j].innerHTML;
          c.addEventListener("click", function(e) {
      
            /*when an item is clicked, update the original select box,
            and the selected item:*/
            var y, i, k, s, h, l, m;
            s = this.parentNode.parentNode.getElementsByTagName("select")[0];
            h = this.parentNode.previousSibling;
            l = this.getElementsByTagName("span")[0];
            m = this.getElementsByTagName("i")[0];
      
      
            for (i = 0; i < s.length; i++) {
              if (s.options[i].innerHTML == l.innerHTML) {
      
                s.selectedIndex = i;
                h.getElementsByTagName("span")[0].innerHTML = l.innerHTML;
                h.getElementsByTagName("i")[0].setAttribute("class", s.options[i].getAttribute('data-icon'));
                y = this.parentNode.getElementsByClassName("same-as-selected");
                for (k = 0; k < y.length; k++) {
                  y[k].removeAttribute("class");
                }
                this.setAttribute("class", "same-as-selected");
                break;
              }
            }
            h.click();
          });
          b.appendChild(c);
        }
        x[i].appendChild(b);
        a.addEventListener("click", function(e) {
          /*when the select box is clicked, close any other select boxes,
          and open/close the current select box:*/
          e.stopPropagation();
          closeAllSelect(this);
          this.nextSibling.classList.toggle("select-hide");
          this.classList.toggle("select-arrow-active");
        });
      }
      
      function closeAllSelect(elmnt) {
        /*a function that will close all select boxes in the document,
        except the current select box:*/
        var x, y, i, arrNo = [];
        x = document.getElementsByClassName("select-items");
        y = document.getElementsByClassName("select-selected");
        for (i = 0; i < y.length; i++) {
          if (elmnt == y[i]) {
            arrNo.push(i)
          } else {
            y[i].classList.remove("select-arrow-active");
          }
        }
        for (i = 0; i < x.length; i++) {
          if (arrNo.indexOf(i)) {
            x[i].classList.add("select-hide");
          }
        }
      }
      /*if the user clicks anywhere outside the select box,
      then close all select boxes:*/
      document.addEventListener("click", closeAllSelect);
      
      
      //////////////////
      //How to get values from custom select
      //////////////////
      document.getElementById("btn1").addEventListener("click", () => {
        console.log(document.getElementById("myselect1").value)
      });
      
      document.getElementById("btn2").addEventListener("click", () => {
        console.log(document.getElementById("myselect2").value)
      });
      .custom-select {
        position: relative;
        font-family: Arial;
      }
      
      .custom-select select {
        display: none;
        /*hide original SELECT element:*/
      }
      
      .custom-select i {
        margin-right: 10px;
      }
      
      .select-selected {
        background-color: DodgerBlue;
      }
      
      
      /*style the arrow inside the select element:*/
      
      .select-selected:after {
        position: absolute;
        content: "";
        top: 14px;
        right: 10px;
        width: 0;
        height: 0;
        border: 6px solid transparent;
        border-color: #fff transparent transparent transparent;
      }
      
      
      /*point the arrow upwards when the select box is open (active):*/
      
      .select-selected.select-arrow-active:after {
        border-color: transparent transparent #fff transparent;
        top: 7px;
      }
      
      
      /*style the items (options), including the selected item:*/
      
      .select-items div,
      .select-selected {
        color: #ffffff;
        padding: 8px 16px;
        border: 1px solid transparent;
        border-color: transparent transparent rgba(0, 0, 0, 0.1) transparent;
        cursor: pointer;
        user-select: none;
      }
      
      
      /*style items (options):*/
      
      .select-items {
        position: absolute;
        background-color: DodgerBlue;
        top: 100%;
        left: 0;
        right: 0;
        z-index: 99;
      }
      
      
      /*hide the items when the select box is closed:*/
      
      .select-hide {
        display: none;
      }
      
      .select-items div:hover,
      .same-as-selected {
        background-color: rgba(0, 0, 0, 0.1);
      }
      <script src="https://kit.fontawesome.com/9593bd7a92.js"></script>
      
      <h2>Custom Select</h2>
      
      <!--surround the select box with a "custom-select" DIV element. Remember to set the width:-->
      <div class="custom-select" style="width:200px;">
        <select id="myselect1">
          <option data-icon="fas fa-truck" value="0">Select car:</option>
          <option data-icon="fas fa-adjust" value="Audi">Audi</option>
          <option data-icon="fas fa-truck" value="BMW">BMW</option>
          <option data-icon="fas fa-arrow-up" value="Citroen">Citroen</option>
          <option data-icon="fas fa-asterisk" value="Ford">Ford</option>
          <option data-icon="fas fa-arrow-left" value="Honda">Honda</option>
          <option data-icon="fas fa-arrow-down" value="Jaguar">Jaguar</option>
      
        </select>
      </div>
      
      <br />
      <div class="custom-select" style="width:200px;">
        <select id="myselect2">
          <option data-icon="fas fa-truck" value="0">Select car:</option>
          <option data-icon="fas fa-adjust" value="Audi">Audi</option>
          <option data-icon="fas fa-truck" value="BMW">BMW</option>
          <option data-icon="fas fa-arrow-up" value="Citroen">Citroen</option>
          <option data-icon="fas fa-asterisk" value="Ford">Ford</option>
          <option data-icon="fas fa-arrow-left" value="Honda">Honda</option>
          <option data-icon="fas fa-arrow-down" value="Jaguar">Jaguar</option>
      
        </select>
      </div>
      
      <br />
      <h3>For testing Purpose<h3>
      
      <button id="btn1">
         Console log Select 1 value
       </button>
      
      
      <button id="btn2">
         Console log Select 2 value
       </button>

      【讨论】:

      • 谢谢!工作得很好。有趣的是,它在除 Mozilla Firefox for DEVELOPERS 之外的所有浏览器中都表现出色:D
      • 我刚刚注意到您的解决方案不适用于手机。任何想法为什么会这样?有图片它在手机中的外观:snipboard.io/nN9zJp.jpg。值得一提的是,我在手机中使用了 DCoder 应用程序来编译代码,因为 StackOverflow 没有在手机版中显示代码片段
      • @vytaute 我不认为它会在手机中工作,因为默认的 html 选择在手机中的处理方式不同。换句话说,选项弹出窗口是由浏览器应用程序生成的,它不是 HTML,它无权访问字体文件
      猜你喜欢
      • 1970-01-01
      • 2016-05-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-07-11
      相关资源
      最近更新 更多