【问题标题】:Change font on mouse over and revert font back when mousing over a second time鼠标悬停时更改字体并在第二次鼠标悬停时恢复字体
【发布时间】:2016-10-30 19:02:39
【问题描述】:

我正在寻找一种在将鼠标悬停在单个字母上时更改其字体的方法。当您第二次将鼠标悬停在单个字母上时(而不是第一次将鼠标移开时),我希望各个字母变回其原始字体。

非常感谢任何和所有帮助!

【问题讨论】:

    标签: javascript css fonts mouseover


    【解决方案1】:

    通过使用类列表

    Documentation

    Browser support

    var elLi = document.querySelectorAll('li');
    
    for (var i = 0; i < elLi.length; i++){
      elLi[i].onmouseover = function(){
        this.classList.toggle("times");
      }
    }
    body {
      font-family: 'Arial';
    }
    li {
      margin: 10px 0;
    }
    .times {
      font-family: 'Times';
    }
    <ul>
      <li>Text 1</li>
      <li>Text 2</li>
    </ul>

    没有类列表

    var elLi = document.querySelectorAll('li');
    
    for (var i = 0; i < elLi.length; i++){
      elLi[i].onmouseover = function(){
        if (hasClass(this, 'times')) {
        	this.className = "";
          // Remove class
        } else {
          // Add class
          this.className = "times";
        }
      }
    }
    
    function hasClass( target, className ) {
        return new RegExp('(\\s|^)' + className + '(\\s|$)').test(target.className);
    }
    body {
      font-family: 'Arial';
    }
    li {
      margin: 10px 0;
    }
    .times {
      font-family: 'Times';
    }
    <ul>
      <li>Text 1</li>
      <li>Text 2</li>
    </ul>

    【讨论】:

      【解决方案2】:

      这是一个简单的 jQuery 示例

      var hoveredCounter = 0;
      $('.post-text').hover(function(){
      
          //hover in
          hoveredCounter++;
          //console.log(hoveredCounter);
      
          if(hoveredCounter == 1){
              $(this).addClass('new-font');//or $(this).css('font-family', 'Arial');
          } else if(hoveredCounter == 2) {
              $(this).removeClass('new-font');//or $(this).css('font-family', 'Verdana');
          }
      }, function(){
          //hover out
      })
      
      .old-font{
          font-family: "Arial";
      }
      
      .old-font.new-font{ /* using 2 classnames so the rule will have bigger priority*/
          font-family: "Verdana"
      }
      

      如果您希望每个字母都可以更改,则需要为每个字母单独设置&lt;span&gt;。您可以通过 https://github.com/davatron5000/Lettering.js 自动执行此操作

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-08-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-05-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多