在 JavaScript 中实现关闭小广告的功能,可以通过监听点击事件来隐藏广告元素。
实现效果:
代码:
<!DOCTYPE html>
<html lang="zh"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>关闭小广告示例</title><style>.ad {width: 300px;height: 100px;background-color: lightblue;position: relative;margin: 20px;padding: 10px;border: 1px solid #000;}.close-btn {position: absolute;top: 5px;right: 5px;cursor: pointer;background-color: red;color: white;border: none;padding: 5px;}</style></head><body><div class="ad"><button class="close-btn">关闭</button><p>这是一个小广告!</p></div><script>const closeButtons = document.querySelectorAll('.close-btn');//方式一closeButtons.forEach(button => {button.addEventListener('click', function() {const ad = this.parentElement;ad.style.display = 'none'; // 隐藏广告});});// //方式二// for (let i = 0; i < closeButtons.length; i++) {// closeButtons[i].addEventListener('click', function() {// const ad = this.parentElement;// ad.style.display = 'none'; // 隐藏广告// });// }</script></body>
</html>
部分代码解析:
方式一:
javascript">const closeButtons = document.querySelectorAll('.close-btn');closeButtons.forEach(button => {button.addEventListener('click', function() {const ad = this.parentElement;ad.style.display = 'none'; // 隐藏广告});});
代码解析:
1. 选择元素:
javascript">const closeButtons = document.querySelectorAll('.close-btn');
- 使用
document.querySelectorAll
方法选择所有带有close-btn
类的元素,并将它们存储在closeButtons
变量中。返回的结果是一个 NodeList(类似数组的对象)。
2. 遍历按钮:
javascript">closeButtons.forEach(button => {
- 使用
forEach
方法遍历每个关闭按钮。
3. 添加事件监听器:
javascript">button.addEventListener('click', function() {
- 为每个按钮添加一个点击事件监听器,当按钮被点击时,将会执行后面的函数。
4. 隐藏广告:
javascript">const ad = this.parentElement;
ad.style.display = 'none'; // 隐藏广告
- 在点击事件处理函数中,
this
代表被点击的按钮。this.parentElement
获取按钮的父元素(假设这是广告的容器),然后将其display
样式设置为'none'
,这会隐藏这个广告元素。
方式二:
javascript">const closeButtons = document.querySelectorAll('.close-btn');for (let i = 0; i < closeButtons.length; i++) {closeButtons[i].addEventListener('click', function() {const ad = this.parentElement;ad.style.display = 'none'; // 隐藏广告});
}
代码解析:
- 使用
for
循环,从0
开始,直到closeButtons.length
,逐个访问每个关闭按钮。 - 使用
closeButtons[i]
来获取当前按钮,并添加点击事件监听器。 this.parentElement
是用于获取当前 DOM 元素的父元素。在事件处理函数中,this
代表触发事件的元素(在你的例子中是关闭按钮),而parentElement
属性则返回该元素的父节点。