当元素被点击时,通过添加类名来切换类,当点击外部时,删除类
在本文中,任务是在点击该元素时切换一个CSS类,而在点击该元素以外的地方,也就是HTML文档中的其他地方,删除该特定类。
方法:这可以在JavaScript的帮助下通过以下步骤轻松完成。
- 我们将首先使用querySelector()方法选择需要切换类的元素和整个HTML文档。
- 接下来,我们需要为两个选定的元素添加 “点击 “事件监听器。
- 在要点击的元素的事件监听器中,我们将使用classList.add()方法添加需要的CSS类。
- 在HTML文档的事件监听器中,我们将首先检查被点击的目标是否是上述所需的元素,然后使用classList.remove()方法删除该类,从而在点击上述元素之外的时候切换该类。
例子:在这个例子中,在HTML文档中定义了一个按钮,一旦它被点击,就会在上面添加 “活动 “CSS类。一旦我们点击HTML文档中的其他地方,这个 “活动 “类也将从按钮上删除。
<!DOCTYPE html>
<html>
<head>
<style>
button {
background-color: green;
color: white;
padding: 10px 24px;
font-size: 18px;
border: none;
font-weight: bold;
transition: all 0.4s;
margin: 300px;
}
.active {
background-color: black;
}
</style>
</head>
<body>
<button>GeeksforGeeks</button>
<script>
// Select the button on which the
// class has to be toggled
const btn = document.querySelector("button");
// Select the entire HTML document
const html = document.querySelector("html");
// Add an event listener for
// a click to the button
btn.addEventListener("click", function (e) {
// Add the required class
btn.classList.add("active");
});
// Add an event listener for a
// click to the html document
html.addEventListener("click", function (e) {
// If the element that is clicked on is
// not the button itself, then remove
// the class that was added earlier
if (e.target !== btn)
btn.classList.remove("active");
});
</script>
</body>
</html>
输出: