用JavaScript突出显示选定的div

时间:2018-11-06 18:06:18

标签: javascript html

我想知道如何使用jquery或JavaScript来应用onclick事件,该事件突出显示所选的div并突出显示其他div。

我有一个动态的名称行,用户可以单击它来查看选定的消息,当用户单击选定的名称时,该名称将带有边框突出显示。是否有一种简单的方法可以实现此类事件而无需进行以下操作。

function swapme(foo) {
  buttons = new Array();
  buttons = document.getElementsByTagName('a');
  for (i = 0; i < buttons.length; i++) {
    if (buttons[i].className === 'active') buttons[i].className = 'inactive';
  }
  document.getElementById('button' + foo).className = 'active';
}
.inactive {
  background: #666;
  border: 1px solid #000;
  color: #FFF;
  padding: 12px
}

.active {
  background: #0F0;
  border: 1px solid #F00;
  color: #F00;
  padding: 12px
}
<html>

<head>
</head>

<body>
  <p>
    <a href="#" onclick="swapme('1'); return false;" class="inactive" id="button1">1</a>
    <a href="#" onclick="swapme('2'); return false;" class="inactive" id="button2">2</a>
    <a href="#" onclick="swapme('3'); return false;" class="inactive" id="button3">3</a>
    <a href="#" onclick="swapme('4'); return false;" class="inactive" id="button4">4</a>
    <a href="#" onclick="swapme('5'); return false;" class="inactive" id="button5">5</a>
  </p>

</body>

</html>

如果有一个简单的解决方法,请提出建议,例如在切换事件或更改时。

也可能不必经历数组循环。

2 个答案:

答案 0 :(得分:1)

您可以使用document.querySelectorAll()来删除循环。

您可以实现以下内容:

  • 单击其中一个名称时
  • 启用当前活动
  • 从当前活动类别中删除活动类别
  • 将活动类添加到所单击的元素

这样,您无需遍历所有按钮。

请注意,您可以使用addEventHandler一次添加所有处理程序,而不是在HTML中添加onclick。这样可以减少代码的耦合,并使其更易于维护。

function swapme(event) {
  // Get current active element(s) 
  document.querySelectorAll('.active')
    // Remove active class
    .forEach(e => e.className = 'inactive');
  // And add the active class to the event target.
  event.target.className = 'active';
  // Prevent default link hanlding
  event.preventDefault();
}

document.querySelectorAll('#container > a')
  .forEach(button => button.addEventListener('click', swapme));
.inactive {
  background: #666;
  border: 1px solid #000;
  color: #FFF;
  padding: 12px
}

.active {
  background: #0F0;
  border: 1px solid #F00;
  color: #F00;
  padding: 12px
}
<html>

<head>
</head>

<body>
  <p id="container">
    <a href="#" class="inactive" id="button1">1</a>
    <a href="#" class="inactive" id="button2">2</a>
    <a href="#" class="inactive" id="button3">3</a>
    <a href="#" class="inactive" id="button4">4</a>
    <a href="#" class="inactive" id="button5">5</a>
  </p>

</body>

</html>

答案 1 :(得分:0)

尝试一下:

let links = document.querySelectorAll('a');
   for (var i = 0; i < links.length; i++) {
    links[i].addEventListener('click', activateClass);
   }
function activateClass(e) {
for (var i = 0; i < links.length; i++) {
    links[i].classList.remove('active');
   }
    e.target.classList.add('active');
}
.active { background:#0F0 ; border:1px solid #F00 ; color:#F00 ; padding:12px }
<p>
    <a href="#">1</a>
    <a href="#">2</a>
    <a href="#">3</a>
</p>