javascript - 单击按钮时更改 div 内容
问题描述
我正在尝试在我的网站上制作某种画廊。有3个按钮,下面放了一些文字和图片。当我单击按钮时,我希望内容发生变化(从按钮 #2 等内容更改)。我怎样才能做到这一点?
<ul>
<a href="">
<li>Btn1</li>
</a>
<a href="">
<li>Btn2</li>
</a>
<a href="">
<li>Btn3</li>
</a>
</ul>
<div class="list-first"">
<p class="list-first list-first-mobile">some text from first btn</p>
<img src="imgs/stock1.jpeg" alt="jpg from first btn" class="list-first-img">
</div>
解决方案
试试这个,希望对你有帮助
document.querySelectorAll('button').forEach((el, i) => {
el.addEventListener("click", () => {
document.querySelectorAll('p').forEach(ed => ed.style.display = "none")
el.nextElementSibling.style.display = "block"
})
})
<style>
.loc-caption:before {
content: attr(title);
display: block;
}
ul {
text-align: center;
padding: 0;
}
li {
width: 25%;
display: inline-block;
vertical-align: top;
}
li img {
max-width: 100%;
height: auto;
}
</style>
<ul>
<li class="loc-caption"><button>ClickME</button>
<p style="display:none" class="list-first list-first-mobile ">
<img src="https://chainimage.com/images/related-pictures-natural-sceneries-beautiful-wallpapers.jpg" alt="jpg from first btn " class="list-first-img "> some text from first btn
</p>
</li>
<li class="loc-caption"><button>ClickME2</button>
<p style="display:none" class="list-first list-first-mobile ">
<img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRwXvWYU5tYrokWILC7lgjmCYqYGvActZnt9q8AcPs4dR7hMTBR" alt="jpg from second btn " class="list-first-img "> some text from second btn
</p>
</li>
<li class="loc-caption"><button>ClickME3</button>
<p style="display:none" class="list-first list-first-mobile ">
<img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTzzP-CJnW3xuNeqqMcNLzK_IFPCywsEKifAWlajEzWcdALIDLI" alt="jpg from third btn " class="list-first-img "> some text from third btn
</p>
</li>
</ul>
推荐阅读
- ios - Xcode - 存档产品转到其他项目而不是 iOS 应用程序
- oracle - Oracle DBMS_UTILITY.GET_TIME
- jmeter - 如何设置 -JlopCount =
在 Jmeter 非 GUI 模式下? - firebase - 如何处理异常“方法'onLogin'在null上被调用”
- node.js - 使用@kubernetes/client-node nodejs api部署虚拟服务
- javascript - 捕获第一个视频帧
- aws-lambda - Terraform API 网关与 Swagger (Localstack) 的集成
- mysql - 用于比较其他表值的 DB 表约束
- c# - 创建操作以根据字符串提供的属性名称分配属性
- google-analytics - BigQuery 中的 GA 实体店访问量?