简介
本站介绍了很多 jQuery 幻灯片插件,它们都很优秀,且功能强大,应用在中大型页面上很合适。但如果你的页面很简单,只想要一个简单纯粹的幻灯片效果,这些插件可能略显臃肿。今天我们不用任何插件,写一个简单的响应式幻灯片。
浏览器兼容
IE10+ ✔ | Edge ✔ | Chrome ✔ | Firefox ✔ | Opera ✔ | Safari ✔ |
制作方法
1、HTML
<div class="dowebok"> <img class="active" src="https://www.dowebok.com/images/1.jpg"> <img src="https://www.dowebok.com/images/2.jpg"> <img src="https://www.dowebok.com/images/3.jpg"> </div>
以上是幻灯片主题代码,下面是导航代码:
<nav class="slider-nav"> <ul> <li class="arrow"> <a class="previous"> <span><</span> </a> </li> <li class="arrow"> <a class="next"> <span>></span> </a> </li> </ul> </nav>
2、CSS
.slider-nav ul { list-style: none; margin: 0; padding: 0; display: -webkit-box; display: flex; -webkit-box-pack: center; justify-content: center; } .slider-nav li { -webkit-box-flex: 2; flex: 2; text-align: center; display: -webkit-box; display: flex; } img { max-width: 100%; display: none; -webkit-box-shadow: 10px 10px 20px 0 rgba(94,47,59,0.2); -moz-box-shadow: 10px 10px 20px 0 rgba(94,47,59,0.2); box-shadow: 10px 10px 20px 0 rgba(94,47,59,0.2); } img.active { display: block; -webkit-animation: fadeImg 0.8s; -moz-animation: fadeImg 0.8s; animation: fadeImg 0.8s; } .slider-nav { margin-top: 20px; } .slider-nav .arrow { flex: 0 0 15%; } .slider-nav a { flex-basis: 100%; display: -webkit-box; display: flex; -webkit-box-align: center; align-items: center; -webkit-justify-content: center; justify-content: center; } .slider-nav span { padding: 5px 10px; font-size: 30px; cursor: pointer; }
再添加淡入淡出的动画效果:
@-webkit-keyframes fadeImg { from { opacity: 0; } to { opacity: 1; } } @-moz-keyframes fadeImg { from { opacity: 0; } to { opacity: 1; } } @keyframes fadeImg { from { opacity: 0; } to { opacity: 1; } }
4、JavaScript
var items = document.querySelectorAll('img'); var itemCount = items.length; var nextItem = document.querySelector('.next'); var previousItem = document.querySelector('.previous'); var count = 0; function showNextItem() { items[count].classList.remove('active'); if (count < itemCount - 1) { count++; } else { count = 0; } items[count].classList.add('active'); console.log(count); } function showPreviousItem() { items[count].classList.remove('active'); if (count > 0) { count--; } else { count = itemCount - 1; } items[count].classList.add('active'); console.log(count); } nextItem.addEventListener('click', showNextItem); previousItem.addEventListener('click', showPreviousItem);
到这里就制作完了,看看效果吧。
[b2_file link="
百度网盘" name="制作简单的响应式幻灯片" pass="" code=""]