简体   繁体   English

单击元素时添加一个类,单击其他位置时将其删除

[英]Add a class when clicked on element, remove it when clicked elsewhere

I need to add a class( .highlight ) to an element when its clicked upon, and it should be removed when clicked either on the element or anywhere else in the document. 我需要在元素上单击时添加一个class( .highlight ),并且在元素上或文档中的任何其他位置单击时都应将其删除。

I have managed to add and remove the class when the element is clicked using the classList.toggle() method but have no idea how to remove the class when a click happens in the document. 当使用classList.toggle()方法单击元素时,我设法添加和删除了该类,但是不知道如何在文档中单击时删除该类。

Here's my HTML, CSS and JS. 这是我的HTML,CSS和JS。

<p class="normal" onclick="detectClick(this)">This is paragraph 1</p>
<p class="normal" onclick="detectClick(this)">This is paragraph 2</p>
<p class="normal" onclick="detectClick(this)">This is paragraph 3</p>

.highlight {
    background-color: yellow;
}

function detectClick(element) {
    element.classList.toggle("highlight");
}

And here's where you can see the code in action, http://codepen.io/vbcda/pen/GodZmr 在这里您可以看到实际的代码, http://codepen.io/vbcda/pen/GodZmr

It can happen if you first remove exiting class 'highlight' from the element by using mousedown event by clicking anywhere in the body. 如果您首先通过单击正文中的任意位置,使用mousedown事件从元素中删除退出的类“突出显示”,则会发生这种情况。

<body onmousedown="outerClick(this)"> // Add this in your html file

function detectClick(element) {
    element.classList.toggle("highlight");
}
function outerClick(el){
  var elements = document.querySelectorAll(".highlight");
  for (var i = 0; i < elements.length; i++) {
      elements[i].classList.remove('highlight');
   }
}

I'd do something like this. 我会做这样的事情。

function detectClick(element) {
  var elements = document.getElementsByClassName("normal");
  Array.from(elements).forEach(function(element) {
    element.setAttribute("class", "normal");
  });
  element.setAttribute("class", "normal highlight");
}

You could be explicit and use document.getElementsByClassName("normal highlight") too. 您可能很明确,也可以使用document.getElementsByClassName(“ normal Highlight”)。

A simple lightweight solution 一个简单的轻量级解决方案

This can be done with just a couple of lines of CSS. 只需使用几行CSS即可完成。 The trick in this case is that you must add the tabindex attribute to each P so that it can receive focus. 在这种情况下,技巧是必须将tabindex属性添加到每个P中,以便它可以获取焦点。

Run the snippet below and click on the text to try. 运行下面的代码段,然后单击文本以尝试。

 p:not(:focus) { background-color: lightgray;} p:focus { background-color: yellow;} 
 <p tabindex=1>This is paragraph 1</p> <p tabindex=2>This is paragraph 2</p> <p tabindex=3>This is paragraph 3</p> 

if you want to use jquery: 如果要使用jQuery:

$('.normal').click(function(e){
  e.stopPropagation();
  $(this).toggleClass('highlight');
});

$(document).click(function(){
  $('.normal').removeClass('highlight');
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM