javascript 中的手动悬停功能

Manual hover function in javascript

我不知道出了什么问题,但是即使我没有悬停按钮,我在这里写的悬停功能仍然存在。我知道悬停对象有更简单的方法,但我正在学习基础知识,因此了解我所拥有的这段确切代码有什么问题会很有帮助。

<head>
  <style>
    .tabStrip {
      background-color: #E4E2D5;
      padding: 15px;
      height: 22px;
      width: 130px;
      margin: auto;
    }

    .tabStrip div {
      float: left;
      font: 14px arial;
      cursor: pointer;
    }

    .tabStrip-tab {
      padding: 5px;
    }

    .tabStrip-tab-hover {
      border: 1px solid #316AC5;
      background-color: #C1D2EE;
      padding: 4px;
    }

    .tabStrip-tab-click {
      border: 1px solid #facc5a;
      background-color: #f9e391;
      padding: 4px;
    }
  </style>

</head>


<body>

  <div class="tabStrip">
    <div data-tab-number="1" class="tabStrip-tab">Tab1</div>
    <div data-tab-number="2" class="tabStrip-tab">Tab2</div>
    <div data-tab-number="3" class="tabStrip-tab">Tab3</div>
  </div>

  <div id="descContainer"></div>

  <script>
    function handleEvent(e) {
      var target = e.target;
      switch (e.type) {
        case 'mouseover':
          if (target.className == 'tabStrip-tab') {
            target.className = 'tabStrip-tab-hover';
          }
          break;
        case 'mouseout':
          if (targer.className == 'tabStrip-tab-hover') {
            targer.className = 'tabStrip-tab';
          }
          break;
        case 'click':
          if (target.className == 'tabStrip-tab-hover') {
            target.className = 'tabStrip-tab-click';
            var num = target.getAttribute('data-tab-number');
            showDescription(num);
          }
          break;
      }
    }

    function showDescription(num) {
      var descContainer = document.getElementById('descContainer')
      var text = 'description for tab ' + num;
      descContainer.innerHTML = text;
    }

    document.addEventListener('mouseover', handleEvent);
    document.addEventListener('mouseout', handleEvent);
    document.addEventListener('click', handleEvent);
  </script>

</body>

问题似乎是您在 javascript

中将 target 拼错为 target

正确:

function handleEvent(e) {
  var target = e.target;
  switch (e.type) {
    case 'mouseover':
      if (target.className == 'tabStrip-tab') {
        target.className = 'tabStrip-tab-hover';
      }
      break;
    case 'mouseout':
      if (target.className == 'tabStrip-tab-hover') {
        target.className = 'tabStrip-tab';
      }
      break;
    case 'click':
      if (target.className == 'tabStrip-tab-hover') {
        target.className = 'tabStrip-tab-click';
        var num = target.getAttribute('data-tab-number');
        showDescription(num);
      }
      break;
  }
}

Codepen of it working correctly

您在 mouseout 事件中的拼写不正确。它是 targer 而不是 `target.

case 'mouseout':
    if (target.className == 'tabStrip-tab-hover') {
        target.className = 'tabStrip-tab';
    }
    break;