search
HomeWeb Front-endJS TutorialjQuery plug-in boxScroll implements image carousel effects_jquery

BoxScroll

Simple implementation of common image carousel effects. It can be controlled by digital list or left and right buttons. The logic is very simple, you have to run back when you reach the end, just look at the comments.

The code is as follows:

HTML

<!doctype html>
<html>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta content="" name="keywords" />
<meta content="" name="description" />
<meta name="author" content="codetker" />
<head>
<title>简易图片轮播插件</title>
<link href="style/reset.css" rel="stylesheet" type="text/css">
<link href="style/style.css" rel="stylesheet" type="text/css">
<script type="text/javascript" src="js/jquery-1.9.1.min.js"></script>
<script type="text/javascript" src="js/jquery.codetker.boxScroll.js"></script>
</head>

<body>
  <div class="wrap">
    <div class="scrollBox">
      <div class="picOuterBox boxStyle">
        <div class="arrow arrowLeft">ToLeft</div>
        <div class="arrow arrowRight">ToRight</div>
        <ul class="picInnerBox boxStyle">
          <li>
            <a href="" title="">
              <img src="/static/imghwm/default1.png"  data-src="images/test.jpg"  class="lazy" alt="">
            </a>
          </li>
          <li>
            <a href="" title="">
              <img src="/static/imghwm/default1.png"  data-src="images/test.jpg"  class="lazy" alt="">
            </a>
          </li>
          <li>
            <a href="" title="">
              <img src="/static/imghwm/default1.png"  data-src="images/test.jpg"  class="lazy" alt="">
            </a>
          </li>
          <li>
            <a href="" title="">
              <img src="/static/imghwm/default1.png"  data-src="images/test.jpg"  class="lazy" alt="">
            </a>
          </li>
          <li>
            <a href="" title="">
              <img src="/static/imghwm/default1.png"  data-src="images/test.jpg"  class="lazy" alt="">
            </a>
          </li>
        </ul>
      </div>
      <div class="picControl">
        <ul>
          <li class="liSelected">1</li>
          <li>2</li>
          <li>3</li>
          <li>4</li>
          <li>5</li>
        </ul>
      </div>
    </div>
  </div>
<script type="text/javascript">
  $(document).ready(function(){
    $(".scrollBox").boxScroll();
  });
</script>
</body>
</html>

CSS

@charset "utf-8";
/* CSS Document */
body{
  margin:0 0;
  padding:0 0;
  height:100%;
  width:100%;
}
.wrap{
  font-family:"微软雅黑","宋体", Times, "Times New Roman", serif;
  font-size:14px;
  margin:0 0;
  padding:0 0;
  height:100%;
  width:100%;
  overflow:hidden;
}
.boxStyle{/*照片大小*/
  width: 500px;
  height: 256px;
}
.scrollBox{
  position: relative;
  width: 500px;
  margin: 0 auto;
}
.picInnerBox{
  width: 10000px;/*足够大能放下即可,如果需要上下滚动,改height*/
  overflow: hidden;
}
.picInnerBox li{
  cursor: pointer;
  float: left;
}
.picOuterBox{
  overflow: hidden;

}
.arrow{
  position: absolute;
  top: 45%;
  height: 40px;
  cursor: pointer;
  z-index: 99;    
}
.arrow:hover{
  color: #fff;
}
.arrowLeft{
  float: left;
  left: 5%;
}
.arrowRight{
  float: right;
  right: 5%;
}
.picControl{
  overflow: auto;
  width: 100px;
  margin: 0 auto;
}
.picControl ul li{
  cursor: pointer;
  float: left;
  width: 20px;
  height: 20px;
  text-align: center;
}
.picControl ul li:hover{
  color:red;
}
.liSelected{
  color: red;
}

JavaScript

/*
 * boxScroll 0.1
 * 兼容等常见浏览器
 */
 ;(function($,window,document,undefined){
   //定义构造函数
   var BoxObj=function(ele,opt){
     this.$element=ele; //最外层对象
     this.defaults={
       'style': 0 ,//滚动样式选择,默认为普通效果
       'speed': 1 ,//默认为1s
       'direction': 'left',//默认为向左边滚动
       'toLeft':$(ele).children('.picOuterBox').children('.arrowLeft'),//默认格式下重要位置
       'toRight':$(ele).children('.picOuterBox').children('.arrowRight'),
       'ControlUl':$(ele).children('.picControl').children('ul')
     },
   
     this.options=$.extend({},this.defaults,opt );
     //这里可以添加一些通用方法  
   }

   //给构造函数添加方法
   BoxObj.prototype={

       commonScroll:function(){
       //接收对象属性
       var boxWindow=$(this.$element).children('.picOuterBox').children('.picInnerBox');
       var speed=this.defaults.speed;
       var style=this.defaults.style;
       var direction=(this.defaults.direction=='left')&#63; 1 : -1;
       var toLeft=this.defaults.toLeft;
       var toRight=this.defaults.toRight;
       var Control=this.defaults.ControlUl;

       var boxWidth=$(boxWindow).children('li').width();
       var imgIndexMax=$(boxWindow).children('li').length;
       var imgIndex;
       function getImgIndex(){//判断当前图片的位置
         imgIndex=Math.round(parseInt($(boxWindow).css("margin-left"))*(-1)/boxWidth);
       }

       var timer;//必须在外面定义保证全局针对这一功能只有这一个计时器
       timer=setInterval(function(){
         boxScroll(imgIndex,direction);
       },5000);

       function rest(){
         clearInterval(timer);
        timer=setInterval(function(){
           boxScroll(imgIndex,direction);
         },5000);
       }

       //绑定点击按钮
       $(Control).delegate('li', 'click', function() {
         boxScroll($(this).index(),0);
         rest();
       });

       //绑定左右按钮
       $(toLeft).click(function() {
         boxScroll(0,-1);
         rest();
       });
       $(toRight).click(function() {
         boxScroll(0,1);
         rest();
       });

       function boxScroll(index,dir){
         if (!$(boxWindow).is(':animated')) {//当ul窗口没有在动时
           if(!dir){//响应ul li control操作
             //此时dir=0,则依靠传入的imgIndex
             imgIndex=index;
             //其它时候dir!=0,则依靠dir
           }else{//响应toLeft和toRight
             if(dir==1){//向右动
               getImgIndex();
               if (imgIndex==(imgIndexMax-1)) {
                 imgIndex=0;

               }else{
                 imgIndex+=1;
               }
             }else{//向左动
               getImgIndex();
               if (imgIndex==0) {
                 imgIndex=(imgIndexMax-1);
               }else{
                 imgIndex-=1;
               }
             }
           }
           $(Control).children('li').eq(imgIndex).addClass('liSelected');
           $(Control).children('li').eq(imgIndex).siblings().removeClass('liSelected');
           $(boxWindow).animate({
               "margin-left":imgIndex*boxWidth*(-1)+'px'
             }, 1000*speed);
         }
       }
     }
   }

   //在插件中使用windowObj对象的方法,0为vertical,1为horizontal
   $.fn.boxScroll=function(options){
     //创建实体
     var boxObj=new BoxObj(this,options);
     //用尾调的形式调用对象方法
     return boxObj.commonScroll();
   }
 })(jQuery,window,document);

For detailed download, please see https://github.com/codetker/myBoxScroll.

The above is the entire content of this article, I hope you all like it.

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript: Exploring the Versatility of a Web LanguageJavaScript: Exploring the Versatility of a Web LanguageApr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

The Evolution of JavaScript: Current Trends and Future ProspectsThe Evolution of JavaScript: Current Trends and Future ProspectsApr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

Demystifying JavaScript: What It Does and Why It MattersDemystifying JavaScript: What It Does and Why It MattersApr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools