21xrx.com
2025-03-26 07:58:14 Wednesday
文章检索 我的文章 写文章
JavaScript实现全屏宽度轮播图
2023-06-16 19:48:39 深夜i     17     0
JavaScript 轮播图 全屏宽度

在网页设计中,轮播图是一种常见且必要的组件。它能够吸引用户的注意力,展示多张图片或者信息,并提高网页的美观度。在这篇文章中,我们将介绍如何使用JavaScript创建出一个宽度占满屏幕的轮播图。

下面是实现这个轮播图的简单代码:

HTML代码:

CSS代码:

#slider
 width: 100%;
 overflow: hidden;
#slider ul
 list-style: none;
 width: 300%;
 transition: all 0.5s;
#slider li
 float: left;
 width: 33.33%;
#slider img
 width: 100%;
 height: auto;

JavaScript代码:

window.onload = function() {
 var slider = document.getElementById('slider');
 var ul = slider.children[0];
 var li = ul.children;
 var arrow = document.getElementById('arrow');
 var prev = document.getElementById('prev');
 var next = document.getElementById('next');
 var index = 0;
 var timer = null;
 // 下一张图片
 function nextPic() {
  index++;
  if (index >= li.length)
   index = 0;
  
  showPic();
 }
 // 上一张图片
 function prevPic() {
  index--;
  if (index < 0)
   index = li.length - 1;
  
  showPic();
 }
 // 显示图片
 function showPic() {
  var target = -index * slider.offsetWidth;
  animate(ul, {left: target});
 }
 // 自动轮播
 function autoPlay() {
  timer = setInterval(function() {
   nextPic();
  }, 2000);
 }
 autoPlay();
 // 鼠标移入、移出
 slider.onmouseover = function() {
  clearInterval(timer);
  arrow.style.display = 'block';
 }
 slider.onmouseout = function() {
  autoPlay();
  arrow.style.display = 'none';
 }
 // 点击上一张、下一张
 prev.onclick = function() {
  prevPic();
 }
 next.onclick = function() {
  nextPic();
 }
}

上述代码中,我们通过CSS将轮播图宽度设置为100%并且溢出隐藏。然后,我们通过JavaScript来进行图片轮播。JavaScript代码中,我们利用`setInterval()`方法来定时自动播放图片,同时通过`onmouseover`和`onmouseout`事件,控制图片的滑动和暂停操作。

  
  

评论区

请求出错了