大家在浏览网站时,有没有注意到导航的样式有很多种,比如面包屑导航、下拉菜单导航,手风琴导航等等,那作为一个前端开发人员,你知道如何用原生js实现手风琴导航效果吗?这篇文章就给大家讲讲原生js制作手风琴效果的思路以及js手风琴效果代码,有一定的参考价值,感兴趣的小伙伴可以看看。
用JS制作手风琴导航需要用到很多JavaScript知识,比如toggle,for循环,if函数等等,如有不清楚的同学可以参考PHP中文网的相关文章,或者访问 JavaScript视频教程,希望可以帮助到你!
实现手风琴导航效果的思路:当鼠标点击第一个按钮时,第一个按钮里面的内容显示出来,点击第二个按钮时,第二个按钮里面的内容显示出来,以此类推。在JavaScript中,用for循环遍历有多少个按钮,用if函数判断maxHeight,从而实现按钮内容的显示和隐藏,具体代码如下:
HTML部分:设置三个按钮以及按钮所对应的内容
<h2>手风琴动画效果</h2> <button>选项 1</button> <div> <p>内容1</p> </div> <button>选项 2</button> <div> <p>内容2</p> </div> <button>选项 3</button> <div> <p>内容3</p><div class="aritcle_card flexRow artxards"> <div class="artcardd flexRow"> <a class="aritcle_card_img" rel="nofollow" href="/xiazai/skill2180" title="baidu-map-jsapi-three"><img src="https://img.php.cn/upload/skill/000/000/081/178885451266383.jpg" alt="baidu-map-jsapi-three" onerror="this.onerror='';this.src='/static/lhimages/moren/morentu.png'" ></a> <div class="aritcle_card_info flexColumn"> <a rel="nofollow" href="/xiazai/skill2180" title="baidu-map-jsapi-three" class="overflowclass">baidu-map-jsapi-three</a> <p class="overflowclass">使用 MapV-Three 构建专业的 3D 地图和 GIS 应用 - 基于 Z-up 坐标系的 3D 地图库,支持地图编辑、测量工具、要素绘制、数据管理等地理可视化功能。适用于创建地图编辑器、测量工具、空间数据可视化等 Web-GIS 应用。</p> </div> <a rel="nofollow" href="/xiazai/skill2180" title="baidu-map-jsapi-three" class="aritcle_card_btn flexRow flexcenter"><b></b><span>下载</span> </a> </div> </div> </div>
CSS部分:用CSS美化页面和实现简单效果,比如当鼠标经过按钮时颜色变深
.btn {
background-color: #eee;
color: #444;
cursor: pointer;
padding: 18px;
width: 100%;
border: none;
text-align: left;
outline: none;
font-size: 15px;
transition: 0.4s;
}
.btn.active,.btn:hover {
background-color: #ddd;
}
.p1 {
padding: 0 18px;
background-color: white;
max-height: 0;
overflow: hidden;
transition: max-height 0.2s ease-out;
}
JavaScript部分:这是手风琴效果的关键部分,它决定了按钮内容能不能隐藏和显示
var btn = document.getElementsByClassName("btn");
for (var i = 0; i <p>效果如下图所示:</p><p><img title="1540439893714545.jpg" alt="图片3.jpg" src="https://img.php.cn//upload/image/572/657/308/1540439893714545.jpg?x-oss-process=image/resize,p_40"></p><p>以上用文字、图片和代码给大家介绍了如何用原生JS实现手风琴导航效果,之前没有接触过的小伙伴一定要自己动手尝试,看看你能不能手写出这样的效果。希望这篇文章对你有所帮助!</p><p>更多相关教程请访问 <a href="http://www.php.cn/course/26.html" target="_blank">JavaScript中文参考手册</a></p>










