jquery 图像滑块_jQuery CSS图像滑块–自行编写代码

jquery 图像滑块

Today we will learn how to make our own jQuery image slider. This Article is a part of “Sliders” series. It’s an introductory tutorial on creating your own Image Slider using CSS and JQuery.

今天,我们将学习如何制作自己的jQuery图像滑块。 本文是“ 滑块 ”系列的一部分。 这是有关使用CSS和JQuery创建自己的Image Slider的入门教程。

jQuery图像滑块 (jQuery Image Slider)

We will cover following topics in this jQuery image slider tutorial. By the end of tutorial, you should be able to create your own simple jQuery image slider.

在本jQuery图像滑块教程中,我们将介绍以下主题。 在教程结束之前,您应该能够创建自己的简单jQuery图像滑块。

  1. Heart of Any Website – Sliders

    任何网站的心脏-滑块
  2. jQuery Image Slider Pre-requisites

    jQuery Image Slider前提条件
  3. Implementing jQuery CSS Image Slider

    实现jQuery CSS Image Slider
    1. jQuery Image Slider Basic Directory Structure

      jQuery Image Slider基本目录结构
    2. One Image/Frame jQuery Slider

      一个图像/框架jQuery滑块
    3. Three Image/Frame jQuery Slider

      三个图像/框架jQuery滑块
    4. Embedding multiple jQuery image sliders on a single Web Page.

      在单个网页上嵌入多个jQuery图像滑块。
  4. jQuery Image Slider Live Demo

    jQuery图像滑块实时演示
  5. What’s next?

    下一步是什么?

任何网站的心脏-滑块 (Heart of Any Website – Sliders)

Image Sliders or Galleries are the main front-page content for any website. It’s always a better choice to create a dynamic moving photo-gallery instead of going for a static page, flooded with Images all around. I would not say to use sliders all around your website but they certainly come handy when you have lots of images. There’re some good reasons to choose these sliders over static contents.

图像滑块画廊是任何网站的主要首页内容。 始终创建动态的动态照片画廊,而不是创建一个静态页面,这是一个更好的选择,因为页面上到处都是图片。 我不会说在整个网站上都使用滑块,但是当您有很多图像时,它们肯定会派上用场。 有很多很好的理由选择这些滑块而不是静态内容。

滑块的优点 (Advantages of Sliders)

  1. Used to highlight important information.

    用于突出显示重要信息。
  2. They can depict who you are and what you are all about.

    他们可以描绘出您是谁以及您的全部身份。
  3. They are more engaging than static content and save a lot of space.

    它们比静态内容更具吸引力,并节省了大量空间。
  4. To create a nice Photo-gallery.

    创建一个漂亮的图库。
  5. Used to distribute the information among various slides and guides the user properly.

    用于在各种幻灯片之间分发信息并正确指导用户。
  6. Gives your webpage a classy look.

    给您的网页优雅的外观。
  7. They can be linked to other websites content to show flash messages.

    它们可以链接到其他网站内容以显示即显消息。

jQuery Image Slider前提条件 (jQuery Image Slider Pre-requisites)

This article assumes readers have basic knowledge about what is a webpage, HTML basic tags, few CSS properties and know-how of JavaScript. You can refer to the www.w3schools.com website for these topics. Those who are familiar with these stuffs can directly start with the Implementing Sliders section.

本文假定读者具有有关什么是网页的基本知识,HTML基本标签,很少CSS属性以及JavaScript的专门知识。 您可以访问www.w3schools.com网站上的这些主题。 那些熟悉这些知识的人可以直接从“实施滑块”部分开始。

实现jQuery CSS Image Slider (Implementing jQuery CSS Image Slider)

Now with some basic background of HTML, CSS and JavaScript, we can proceed with the slider implementation. Just follow the following guidelines.

现在,有了HTML,CSS和JavaScript的一些基本背景,我们就可以继续执行滑块了。 只需遵循以下准则。

  1. jQuery Image Slider基本目录结构 (jQuery Image Slider Basic Directory Structure)

    jquery image slider directory structure

    Let’s organize different resources among folders in our Root directory.

    • “SimplePhotoSlider” is our Root folder having HTML files with other sub-folders.
    • “scripts” folder contains the Javascript libraries such as JQuery and some other script files.
    • “styles” folder contains CSS files defining styles of different HTML tags.
    • “images” folder contains two sub-folders for storing images of different dimensions.


    让我们在“根”目录中的文件夹之间组织不同的资源。

    • “ SimplePhotoSlider”是我们的Root文件夹,其中包含带有其他子文件夹HTML文件。
    • “ scripts”文件夹包含Javascript库,例如JQuery和其他一些脚本文件。
    • “ styles”文件夹包含CSS文件,这些CSS文件定义了不同HTML标记的样式。
    • “图像”文件夹包含两个子文件夹,用于存储不同尺寸的图像。
  2. 一张照片/框架jQuery滑块 (One Photo/Frame jQuery Slider)

    One photo per frame means at a time you will be seeing only one slide. This slider will only have slides moving along with two navigation controls named “Next” and “Previous”. The layout of the slider is as shown in the figure.

    The SimpleSlider.html file has structural elements along with scripts related to creation of the object for our slider. Observe how each of the slide images is enlisted as the unordered list elements. Two files simpleStyle.css and simpleSliderScript.js contain styles and methods for controlling the slider motion and direction. You would also need reference to JQuery Library i.e. https://code.jquery.com/jquery-2.1.0.js which you can download and save in the folder “scripts”.

    Explanation of simpleSliderScript.js

    • slider() method accepts two parameters and extracts some information like no. of images in the list and width of the image.
    • The “transition” object in the simpleSliderScript.js file calculates the displacement at each move, and which is equal to width of the slide images.
    • The “setCurrentPos” object calculates the value of “current” counter after the user click on navigation buttons.
    • Based on Next or Previous button pressed, the value of current is either incremented or decremented. Also if “current” goes below 0, then it’s set to the last element in the list.

    Codes for all these files are as shown below.

    HTML Code

    SimpleSlider.html

    CSS Code

    simpleStyle.css

    *
    {
    	margin:0;
    	padding:0;
    }
    
    .gallery
    {
    	width:640px;
    	height:370px;
    	margin:10px auto;
    	background:#999;
    	border:1px solid orange;
    }
    
    .slider
    {
    	width:inherit;
    	height:344px;
    	overflow:scroll;
    }
    .slider ul
    {
    	width:10000px;
    	list-style:none;
    	margin-left:0px;
    }
    .slider li
    {
    	float:left;
    }
    
    #slider-nav
    {
    	display:none; /* This is important to hide the buttons if jQuery is Not supported. */
    	margin-top: -10em;
    	cursor: pointer;		
    }

    JavaScript Code

    simpleSliderScript.js

    The source codes have comments wherever it is needed. In case of specific doubt you can ask me directly through comments.

    Simple Image Slider Output

    jQuery image slider, CSS image slider

    每帧一张照片意味着您一次只能看到一张幻灯片。 该滑块仅具有与两个名为“下一个”和“上一个”的导航控件一起移动的幻灯片。 滑块的布局如图所示。

    SimpleSlider.html文件包含结构元素以及与为滑块创建对象有关的脚本。 观察每个幻灯片图像如何被列为无序列表元素。 两个文件simpleStyle.csssimpleSliderScript.js包含用于控制滑块运动和方向的样式和方法。 您还需要引用JQuery库,即https://code.jquery.com/jquery-2.1.0.js ,您可以下载并保存在“ scripts”文件夹中。

    simpleSliderScript.js的说明

    • Slider()方法接受两个参数并提取一些信息,例如no。 图片列表和图片宽度中的图片。
    • simpleSliderScript.js文件中的“ transition”对象计算每次移动时的位移,该位移等于幻灯片图像的宽度。
    • 用户单击导航按钮后,“ setCurrentPos”对象将计算“当前”计数器的值。
    • 基于按下的“ 下一个”或“ 上一个”按钮,电流值将增加或减少。 同样,如果“当前”值低于0,则将其设置为列表中的最后一个元素。

    所有这些文件的代码如下所示。

    HTML代码

    SimpleSlider.html

    <!Doctype html>
    <html>
    	<head>
    		<title>Simple Slider</title>
    		<link rel="stylesheet" href="styles/simpleStyle.css">		
    	</head>
    	<body>
    		<!-- Container for Slider and Navigation Controls -->
    		<div class="gallery">
    			<h2>Photo Slider</h2>
    			<!-- The actual moving Slider -->
    			<div class="slider">
    				<ul>
    					<li><img src="images/bigimg/bigimg1.jpeg" class="slides" alt="Image1"></li>
    					<li><img src="images/bigimg/bigimg2.jpeg" class="slides" alt="Image2"></li>
    					<li><img src="images/bigimg/bigimg3.jpeg" class="slides" alt="Image3"></li>
    					<li><img src="images/bigimg/bigimg4.jpeg" class="slides" alt="Image4"></li>
    				</ul>
    			</div>
    			<!-- Navigation Button Controls -->
    			<div id="slider-nav">
    				<button data-dir="prev">Previous</button>
    				<button data-dir="next" style="float:right;">Next</button>
    			</div>
    		</div>
    		<!-- Loading JavaScript Codes. -->
    		<script src="scripts/jquery-2.1.0.js"></script>
    		<script src="scripts/simpleSliderScript.js"></script>
    		<script>
    			// 
    			jQuery(document).ready(function ($) {
    				// creating a container variable to hold the 'UL' elements. It uses method chaining.
    				var container=$('div.slider')
    											.css('overflow','hidden')
    											.children('ul');
    				
    				/* 
    				On the event of mouse-hover, 
    					i) Change the visibility of Button Controls.
    					ii) SET/RESET the "intv" variable to switch between AutoSlider and Stop mode.
    				*/
    				$('.gallery').hover(function( e ){
    					$('#slider-nav').toggle();
    					return e.type=='mouseenter'?clearInterval(intv):autoSlider();
    				});
    				
    				// Creating the 'slider' instance which will set initial parameters for the Slider.
    				var sliderobj= new slider(container,$('#slider-nav'));
    				/*
    				This will trigger the 'setCurrentPos' and 'transition' methods on click of any button
    				 "data-dir" attribute associated with the button will determine the direction of sliding.
    				*/
    				sliderobj.nav.find('button').on('click', function(){
    					sliderobj.setCurrentPos($(this).data('dir'));
    					sliderobj.transition();
    				});
    				
    				autoSlider(); // Calling autoSlider() method on Page Load.
    				
    				/* 
    				This function will initialize the interval variable which will cause execution of the inner function after every 2 seconds automatically.
    				*/
    				function autoSlider()
    				{
    					return intv = setInterval(function(){
    						sliderobj.setCurrentPos('next');
    						sliderobj.transition();
    					}, 2000);
    				}
    				
    			});
    		</script>
    	</body>
    </html>

    CSS代码

    simpleStyle.css

    JavaScript代码

    simpleSliderScript.js

    /*
    This method will initialize each slider instance.
    */
    function slider(container, nav){
    	this.container=container;
    	this.nav=nav.hide(); // This will assign 'nav' from parameters to 'nav' of current slider instance. It uses method chaining.
    	this.imgs=this.container.find('.slides'); // Returns jQuery object containing all matched elements.
        console.log('Value of this.imgs is : '+this.imgs);
    	this.width=this.imgs[0].width;
    	console.log('Value of width is : '+this.width);
    	this.imgLen=this.imgs.length; // Returns the total number of sliding elements.
    	/* 	Initialize the "current" counter. 
    		This counter keeps track of the index of current slide in the unordered list of elements. 
    		This will be used for calculating the required displacement.
    	*/
    	this.current=0; // Initialize the "current" counter.
    }
    
    // This method will apply the needed animation and displacement.
    slider.prototype.transition=function(coords){
    	this.container.animate({
    		'margin-left': coords || -(this.current*this.width) // First element is multiplied by Zero.
    	},500);
    };
    
    // This method will set the "current" counter to next position.
    slider.prototype.setCurrentPos=function(dir){
    	var pos=this.current;
    	console.log('Value of this.value is : '+dir);
    	// It'll check which button is pressed and accordingly increments or decrements the 'pos' variable.
    	pos+= ~~(dir=='next') || -1; // You can use alternate "Math.floor()" method instead of double tilde (~~) operator.
    	this.current=(pos<0)?this.imgLen-1: pos%(this.imgLen);
    	console.log(this.current);
    	
    };

    源代码在任何需要的地方都有注释。 如有特殊疑问,您可以通过评论直接问我。

    简单的图像滑块输出

  3. 多图像/框架jQuery滑块 (Multi Images/Frame jQuery Slider)

    • Three Photos per Frame means you can see three slides at a time. After properly understanding the Simple One Photo per Frame slider, it should be easy to grasp new changes made in this slider.
    • A new object called “divider” is introduced between two slides which can be any image of specified dimension. So the “transition” object in the multiImageSliderScript.js file has been modified to accommodate the gap (which also includes divider’s width) between any two slides.
    • Also “setCurrentPos” object has a little change which can be easily understood.
    • As you could see from the code MultiImageSlider.html, that unordered list has been modified a little bit to add the divider between two consecutive slide elements.

    Codes for all these files are as shown below.

    HTML Code

    MultiImageSlider.html

    <!Doctype html>
    <html>
    	<head>
    		<title>Multiple Image Slider</title>
    		<link rel="stylesheet" href="styles/multiImageStyle.css">		
    	</head>
    	<body>
    		<!-- Container for Slider and Navigation Controls -->
    		<div class="gallery">
    			<h2>MultiImage Slider</h2>
    			<!-- The actual moving Slider with Slides and Dividers-->
    			<div class="slider">
    				<ul>
    					<li><img src="images/smallimg/smallimg1.png" class="slides" alt="Image1"><img src="images/smallimg/SmallDivider.jpg" class="dividers" alt="Divider"></li>
    					<li><img src="images/smallimg/smallimg2.png" class="slides" alt="Image2"><img src="images/smallimg/SmallDivider.jpg" class="dividers" alt="Divider"></li>
    					<li><img src="images/smallimg/smallimg3.png" class="slides" alt="Image3"><img src="images/smallimg/SmallDivider.jpg" class="dividers" alt="Divider"></li>
    					<li><img src="images/smallimg/smallimg4.png" class="slides" alt="Image4"><img src="images/smallimg/SmallDivider.jpg" class="dividers" alt="Divider"></li>
    					<li><img src="images/smallimg/smallimg1.png" class="slides" alt="Image1"><img src="images/smallimg/SmallDivider.jpg" class="dividers" alt="Divider"></li>
    					<li><img src="images/smallimg/smallimg2.png" class="slides" alt="Image2"><img src="images/smallimg/SmallDivider.jpg" class="dividers" alt="Divider"></li>
    					<li><img src="images/smallimg/smallimg3.png" class="slides" alt="Image3"><img src="images/smallimg/SmallDivider.jpg" class="dividers" alt="Divider"></li>
    					<li><img src="images/smallimg/smallimg4.png" class="slides" alt="Image4"></li>	
    				</ul>
    			</div>
    			<!-- Navigation Button Controls -->
    			<div id="slider-nav">
    				<button data-dir="prev">Previous</button>
    				<button data-dir="next" style="float:right;">Next</button>
    			</div>
    		</div>
    		<!-- Loading JavaScript Codes. -->
    		<script src="scripts/jquery-2.1.0.js"></script>
    		<script src="scripts/multiImageSliderScript.js"></script>
    		<script>
    			// 
    			jQuery(document).ready(function ($) {
    				// creating a container variable to hold the 'UL' elements. It uses method chaining.
    				var container=$('div.slider')
    											.css('overflow','hidden')
    											.children('ul');
    				
    				/* 
    				On the event of mouse-hover, 
    					i) Change the visibility of Button Controls.
    					ii) SET/RESET the "intv" variable to switch between AutoSlider and Stop mode.
    				*/
    				$('.gallery').hover(function( e ){
    					$('#slider-nav').toggle();
    					return e.type=='mouseenter'?clearInterval(intv):autoSlider();
    				});
    				
    				// Creating the 'slider' instance which will set initial parameters for the Slider.
    				var sliderobj= new slider(container,$('#slider-nav'));
    				/*
    				This will trigger the 'setCurrentPos' and 'transition' methods on click of any button
    				 "data-dir" attribute associated with the button will determine the direction of sliding.
    				*/
    				sliderobj.nav.find('button').on('click', function(){
    					sliderobj.setCurrentPos($(this).data('dir'));
    					sliderobj.transition();
    				});
    				
    				autoSlider(); // Calling autoSlider() method on Page Load.
    				
    				/* 
    				This function will initialize the interval variable which will cause execution of the inner function after every 2 seconds automatically.
    				*/
    				function autoSlider()
    				{
    					return intv = setInterval(function(){
    						sliderobj.setCurrentPos('next');
    						sliderobj.transition();
    					}, 2000);
    				}
    				
    			});
    		</script>
    	</body>
    </html>

    CSS Code

    multiImageStyle.css

    JavaScript Code

    multiImageSliderScript.js

    /*
    This method will initialize each slider instance.
    */
    function slider(container, nav){
    	this.container=container;
    	this.nav=nav.hide(); // This will assign 'nav' from parameters to 'nav' of current slider instance. It uses method chaining.
    	this.imgs=this.container.find('.slides'); // Returns jQuery object containing all matched elements.
        console.log('Value of this.imgs is : '+this.imgs);
    	this.width=this.imgs[0].width;
    	console.log('Value of width is : '+this.width);
    	this.imgLen=this.imgs.length; // Returns the total number of sliding elements.
    	/* 	Initialize the "current" counter. 
    		This counter keeps track of the index of current slide in the unordered list of elements. 
    		This will be used for calculating the required displacement.
    	*/
    	this.current=0; 
    }
    
    // This method will apply the needed animation and displacement.
    slider.prototype.transition=function(coords){
    	this.container.animate({
    		'margin-left': coords || -(this.current*this.width+35*this.current) // First element is multiplied by Zero. The number 35 is the actual gap between two slides.
    	},500);
    };
    
    // This method will set the "current" counter to next position.
    slider.prototype.setCurrentPos=function(dir){
    	var pos=this.current;
    	console.log('Value of this.value is : '+dir);
    	// It'll check which button is pressed and accordingly increments or decrements the 'pos' variable.
    	pos+= ~~(dir=='next') || -1; // You can use alternate "Math.floor()" method instead of double tilde (~~) operator.
    	this.current=(pos<0)?this.imgLen-3: pos%(this.imgLen-2);
    	console.log(this.current);
    	
    };

    Multi Images/Frame Slider Output

    • 每帧三张照片意味着您一次可以看到三张幻灯片。 正确理解“每帧简单一张照片”滑块后,应该很容易掌握在此滑块中所做的新更改。
    • 在两个幻灯片之间引入了一个称为“分隔线”的新对象,该幻灯片可以是任何指定尺寸的图像。 因此,对multiImageSliderScript.js文件中的“转换”对象进行了修改,以适应任何两张幻灯片之间的间隙(还包括分隔线的宽度)。
    • 同样,“ setCurrentPos”对象也有一点变化,这很容易理解。
    • 从代码MultiImageSlider.html中可以看到,该无序列表已经过一些修改,可以在两个连续的幻灯片元素之间添加分隔符。

    所有这些文件的代码如下所示。

    HTML代码

    MultiImageSlider.html

    <!Doctype html>
    <html>
    	<head>
    		<title>Multiple Image Slider</title>
    		<link rel="stylesheet" href="styles/multiImageStyle.css">		
    	</head>
    	<body>
    		<!-- Container for Slider and Navigation Controls -->
    		<div class="gallery">
    			<h2>MultiImage Slider</h2>
    			<!-- The actual moving Slider with Slides and Dividers-->
    			<div class="slider">
    				<ul>
    					<li><img src="images/smallimg/smallimg1.png" class="slides" alt="Image1"><img src="images/smallimg/SmallDivider.jpg" class="dividers" alt="Divider"></li>
    					<li><img src="images/smallimg/smallimg2.png" class="slides" alt="Image2"><img src="images/smallimg/SmallDivider.jpg" class="dividers" alt="Divider"></li>
    					<li><img src="images/smallimg/smallimg3.png" class="slides" alt="Image3"><img src="images/smallimg/SmallDivider.jpg" class="dividers" alt="Divider"></li>
    					<li><img src="images/smallimg/smallimg4.png" class="slides" alt="Image4"><img src="images/smallimg/SmallDivider.jpg" class="dividers" alt="Divider"></li>
    					<li><img src="images/smallimg/smallimg1.png" class="slides" alt="Image1"><img src="images/smallimg/SmallDivider.jpg" class="dividers" alt="Divider"></li>
    					<li><img src="images/smallimg/smallimg2.png" class="slides" alt="Image2"><img src="images/smallimg/SmallDivider.jpg" class="dividers" alt="Divider"></li>
    					<li><img src="images/smallimg/smallimg3.png" class="slides" alt="Image3"><img src="images/smallimg/SmallDivider.jpg" class="dividers" alt="Divider"></li>
    					<li><img src="images/smallimg/smallimg4.png" class="slides" alt="Image4"></li>	
    				</ul>
    			</div>
    			<!-- Navigation Button Controls -->
    			<div id="slider-nav">
    				<button data-dir="prev">Previous</button>
    				<button data-dir="next" style="float:right;">Next</button>
    			</div>
    		</div>
    		<!-- Loading JavaScript Codes. -->
    		<script src="scripts/jquery-2.1.0.js"></script>
    		<script src="scripts/multiImageSliderScript.js"></script>
    		<script>
    			// 
    			jQuery(document).ready(function ($) {
    				// creating a container variable to hold the 'UL' elements. It uses method chaining.
    				var container=$('div.slider')
    											.css('overflow','hidden')
    											.children('ul');
    				
    				/* 
    				On the event of mouse-hover, 
    					i) Change the visibility of Button Controls.
    					ii) SET/RESET the "intv" variable to switch between AutoSlider and Stop mode.
    				*/
    				$('.gallery').hover(function( e ){
    					$('#slider-nav').toggle();
    					return e.type=='mouseenter'?clearInterval(intv):autoSlider();
    				});
    				
    				// Creating the 'slider' instance which will set initial parameters for the Slider.
    				var sliderobj= new slider(container,$('#slider-nav'));
    				/*
    				This will trigger the 'setCurrentPos' and 'transition' methods on click of any button
    				 "data-dir" attribute associated with the button will determine the direction of sliding.
    				*/
    				sliderobj.nav.find('button').on('click', function(){
    					sliderobj.setCurrentPos($(this).data('dir'));
    					sliderobj.transition();
    				});
    				
    				autoSlider(); // Calling autoSlider() method on Page Load.
    				
    				/* 
    				This function will initialize the interval variable which will cause execution of the inner function after every 2 seconds automatically.
    				*/
    				function autoSlider()
    				{
    					return intv = setInterval(function(){
    						sliderobj.setCurrentPos('next');
    						sliderobj.transition();
    					}, 2000);
    				}
    				
    			});
    		</script>
    	</body>
    </html>

    CSS代码

    multiImageStyle.css

    JavaScript代码

    multiImageSliderScript.js

    /*
    This method will initialize each slider instance.
    */
    function slider(container, nav){
    	this.container=container;
    	this.nav=nav.hide(); // This will assign 'nav' from parameters to 'nav' of current slider instance. It uses method chaining.
    	this.imgs=this.container.find('.slides'); // Returns jQuery object containing all matched elements.
        console.log('Value of this.imgs is : '+this.imgs);
    	this.width=this.imgs[0].width;
    	console.log('Value of width is : '+this.width);
    	this.imgLen=this.imgs.length; // Returns the total number of sliding elements.
    	/* 	Initialize the "current" counter. 
    		This counter keeps track of the index of current slide in the unordered list of elements. 
    		This will be used for calculating the required displacement.
    	*/
    	this.current=0; 
    }
    
    // This method will apply the needed animation and displacement.
    slider.prototype.transition=function(coords){
    	this.container.animate({
    		'margin-left': coords || -(this.current*this.width+35*this.current) // First element is multiplied by Zero. The number 35 is the actual gap between two slides.
    	},500);
    };
    
    // This method will set the "current" counter to next position.
    slider.prototype.setCurrentPos=function(dir){
    	var pos=this.current;
    	console.log('Value of this.value is : '+dir);
    	// It'll check which button is pressed and accordingly increments or decrements the 'pos' variable.
    	pos+= ~~(dir=='next') || -1; // You can use alternate "Math.floor()" method instead of double tilde (~~) operator.
    	this.current=(pos<0)?this.imgLen-3: pos%(this.imgLen-2);
    	console.log(this.current);
    	
    };

    多图像/帧滑块输出

  4. 在单个网页上嵌入多个jQuery图像滑块 (Embedding multiple jQuery image sliders on a single Web Page)

    • In this section, we’ll learn how to add more than one slider in a single webpage itself. If you observe previous codes, you’ll observe that our slider is enclosed within the ‘gallery’ div element.
    • So in the same way we’ll add a new gallery div element with exactly the same contents and we will give them a different name for CLASS and ID property wherever required.
    • Accordingly the CSS file has to be modified to create two sets of styling, one for gallery-1 and other for gallery-2.
    • The only change in multiSliderScript.js file is that we’re modifying the ‘setCurrentPos’ object to check for ‘Next button of both the sliders.

    Codes for all these files are as shown below.

    HTML Code
    MultiSlider.html

    <!Doctype html>
    <html>
    	<head>
    		<title>Multiple Slider on Single Page</title>
    		<link rel="stylesheet" href="styles/multiStyle.css">		
    	</head>
    	<body>
    		<!-- Container for Slider and Navigation Controls -->
    		<!-- This is First Slider. -->
    		<div class="gallery_1">
    			<h2>MultiImage Slider-1</h2>
    			<!-- The actual moving Slider with Slides and Dividers-->
    			<div class="slider_1">
    				<ul>
    					<li><img src="images/smallimg/smallimg1.png" class="slides" alt="Image1"><img src="images/smallimg/SmallDivider.jpg" class="dividers" alt="Divider"></li>
    					<li><img src="images/smallimg/smallimg2.png" class="slides" alt="Image2"><img src="images/smallimg/SmallDivider.jpg" class="dividers" alt="Divider"></li>
    					<li><img src="images/smallimg/smallimg3.png" class="slides" alt="Image3"><img src="images/smallimg/SmallDivider.jpg" class="dividers" alt="Divider"></li>
    					<li><img src="images/smallimg/smallimg4.png" class="slides" alt="Image4"><img src="images/smallimg/SmallDivider.jpg" class="dividers" alt="Divider"></li>
    					<li><img src="images/smallimg/smallimg1.png" class="slides" alt="Image1"><img src="images/smallimg/SmallDivider.jpg" class="dividers" alt="Divider"></li>
    					<li><img src="images/smallimg/smallimg2.png" class="slides" alt="Image2"><img src="images/smallimg/SmallDivider.jpg" class="dividers" alt="Divider"></li>
    					<li><img src="images/smallimg/smallimg3.png" class="slides" alt="Image3"><img src="images/smallimg/SmallDivider.jpg" class="dividers" alt="Divider"></li>
    					<li><img src="images/smallimg/smallimg4.png" class="slides" alt="Image4"></li>	
    				</ul>
    			</div>
    			<!-- Navigation Button Controls -->
    			<div id="slider-nav_1">
    				<button data-dir="prev_1">Previous</button>
    				<button data-dir="next_1" style="float:right;">Next</button>
    			</div>
    		</div>
    		
    		<!-- This is Second Slider. -->
    		<div class="gallery_2">
    			<h2>MultiImage Slider-2</h2>
    			<!-- The actual moving Slider with Slides and Dividers-->
    			<div class="slider_2">
    				<ul>
    					<li><img src="images/smallimg/smallimg1.png" class="slides" alt="Image1"><img src="images/smallimg/SmallDivider.jpg" class="dividers" alt="Divider"></li>
    					<li><img src="images/smallimg/smallimg2.png" class="slides" alt="Image2"><img src="images/smallimg/SmallDivider.jpg" class="dividers" alt="Divider"></li>
    					<li><img src="images/smallimg/smallimg3.png" class="slides" alt="Image3"><img src="images/smallimg/SmallDivider.jpg" class="dividers" alt="Divider"></li>
    					<li><img src="images/smallimg/smallimg4.png" class="slides" alt="Image4"><img src="images/smallimg/SmallDivider.jpg" class="dividers" alt="Divider"></li>
    					<li><img src="images/smallimg/smallimg1.png" class="slides" alt="Image1"><img src="images/smallimg/SmallDivider.jpg" class="dividers" alt="Divider"></li>
    					<li><img src="images/smallimg/smallimg2.png" class="slides" alt="Image2"><img src="images/smallimg/SmallDivider.jpg" class="dividers" alt="Divider"></li>
    					<li><img src="images/smallimg/smallimg3.png" class="slides" alt="Image3"><img src="images/smallimg/SmallDivider.jpg" class="dividers" alt="Divider"></li>
    					<li><img src="images/smallimg/smallimg4.png" class="slides" alt="Image4"></li>	
    				</ul>
    			</div>
    			<!-- Navigation Button Controls -->
    			<div id="slider-nav_2">
    				<button data-dir="prev_2">Previous</button>
    				<button data-dir="next_2" style="float:right;">Next</button>
    			</div>
    		</div>
    		
    		
    		<!-- Loading JavaScript Codes. -->
    		<script src="scripts/jquery-2.1.0.js"></script>
    		<script src="scripts/multiSliderScript.js"></script>
    		<script>
    			// 
    			jQuery(document).ready(function ($) {
    				// creating a container variable to hold the 'UL' elements. It uses method chaining.
    				var container_1=$('div.slider_1')
    											.css('overflow','hidden')
    											.children('ul');
    				
    				var container_2=$('div.slider_2')
    											.css('overflow','hidden')
    											.children('ul');
    				
    				/* 
    				On the event of mouse-hover, 
    					i) Change the visibility of Button Controls.
    					ii) SET/RESET the "intv" variable to switch between AutoSlider and Stop mode.
    				*/
    				$('.gallery_1').hover(function( e ){
    					$('#slider-nav_1').toggle();
    					return e.type=='mouseenter'?clearInterval(intv_1):autoSlider_1();
    				});
    				
    				$('.gallery_2').hover(function( e ){
    					$('#slider-nav_2').toggle();
    					return e.type=='mouseenter'?clearInterval(intv_2):autoSlider_2();
    				});
    				
    				// Creating the 'slider' instance which will set initial parameters for the Slider.
    				var sliderobj_1= new slider(container_1,$('#slider-nav_1'));
    				var sliderobj_2= new slider(container_2,$('#slider-nav_2'));
    				/*
    				This will trigger the 'setCurrentPos' and 'transition' methods on click of any button
    				 "data-dir" attribute associated with the button will determine the direction of sliding.
    				*/
    				sliderobj_1.nav.find('button').on('click', function(){
    					sliderobj_1.setCurrentPos($(this).data('dir'));
    					sliderobj_1.transition();
    				});
    				
    				sliderobj_2.nav.find('button').on('click', function(){
    					sliderobj_2.setCurrentPos($(this).data('dir'));
    					sliderobj_2.transition();
    				});
    				
    				// Calling autoSlider() method on Page Load.
    				autoSlider_1();
    				autoSlider_2(); 
    				
    				/* 
    				This function will initialize the interval variable which will cause execution of the inner function after every 2 seconds automatically.
    				*/
    				function autoSlider_1()
    				{
    					return intv_1 = setInterval(function(){
    						sliderobj_1.setCurrentPos('next_1');
    						sliderobj_1.transition();
    					}, 2000);
    				}
    				
    				function autoSlider_2()
    				{
    					return intv_2 = setInterval(function(){
    						sliderobj_2.setCurrentPos('next_2');
    						sliderobj_2.transition();
    					}, 2000);
    				}
    				
    			});
    		</script>
    	</body>
    </html>

    CSS Code

    multiStyle.css

    JavaScript Code

    multiSliderScript.js

    /*
    This method will initialize each slider instance.
    */
    function slider(container, nav){
    	this.container=container;
    	this.nav=nav.hide(); // This will assign 'nav' from parameters to 'nav' of current slider instance. It uses method chaining.
    	this.imgs=this.container.find('.slides'); // Returns jQuery object containing all matched elements.
        console.log('Value of this.imgs is : '+this.imgs);
    	this.width=this.imgs[0].width;
    	console.log('Value of width is : '+this.width);
    	this.imgLen=this.imgs.length; // Returns the total number of sliding elements.
    	/* 	Initialize the "current" counter. 
    		This counter keeps track of the index of current slide in the unordered list of elements. 
    		This will be used for calculating the required displacement.
    	*/
    	this.current=0; // Initialize the "current" counter.
    }
    
    // This method will apply the needed animation and displacement.
    slider.prototype.transition=function(coords){
    	this.container.animate({
    		'margin-left': coords || -(this.current*this.width+35*this.current) // First element is multiplied by Zero. The number 35 is the actual gap between two slides.
    	},500);
    };
    
    // This method will set the "current" counter to next position.
    slider.prototype.setCurrentPos=function(dir){
    	var pos=this.current;
    	console.log('Value of this.value is : '+dir);
    	// It'll check which button is pressed and accordingly increments or decrements the 'pos' variable.
    	pos+= ~~(dir=='next_1' || dir=='next_2') || -1; // You can use alternate "Math.floor()" method instead of double tilde (~~) operator.
    	this.current=(pos<0)?this.imgLen-3: pos%(this.imgLen-2);
    	console.log(this.current);
    	
    };

    Multi Slider Output

    NOTE: If you are using Chrome browser and want to debug your scripts, you can Press [F12] key and click on “Console” tab to see how “current” counter is changing on click of a button.

    • 在本节中,我们将学习如何在单个网页本身中添加多个滑块。 如果您遵循以前的代码,则会发现我们的滑块包含在“ gallery” div元素内。
    • 因此,以相同的方式,我们将添加一个具有完全相同内容的新gallery div元素,并在需要时为它们赋予CLASS和ID属性一个不同的名称。
    • 因此,必须修改CSS文件以创建两组样式,一组用于gallery-1,另一组用于gallery-2。
    • multiSliderScript.js文件中的唯一变化是,我们正在修改“ setCurrentPos”对象,以检查两个滑块的“下一步”按钮。

    所有这些文件的代码如下所示。

    HTML代码
    MultiSlider.html

    <!Doctype html>
    <html>
    	<head>
    		<title>Multiple Slider on Single Page</title>
    		<link rel="stylesheet" href="styles/multiStyle.css">		
    	</head>
    	<body>
    		<!-- Container for Slider and Navigation Controls -->
    		<!-- This is First Slider. -->
    		<div class="gallery_1">
    			<h2>MultiImage Slider-1</h2>
    			<!-- The actual moving Slider with Slides and Dividers-->
    			<div class="slider_1">
    				<ul>
    					<li><img src="images/smallimg/smallimg1.png" class="slides" alt="Image1"><img src="images/smallimg/SmallDivider.jpg" class="dividers" alt="Divider"></li>
    					<li><img src="images/smallimg/smallimg2.png" class="slides" alt="Image2"><img src="images/smallimg/SmallDivider.jpg" class="dividers" alt="Divider"></li>
    					<li><img src="images/smallimg/smallimg3.png" class="slides" alt="Image3"><img src="images/smallimg/SmallDivider.jpg" class="dividers" alt="Divider"></li>
    					<li><img src="images/smallimg/smallimg4.png" class="slides" alt="Image4"><img src="images/smallimg/SmallDivider.jpg" class="dividers" alt="Divider"></li>
    					<li><img src="images/smallimg/smallimg1.png" class="slides" alt="Image1"><img src="images/smallimg/SmallDivider.jpg" class="dividers" alt="Divider"></li>
    					<li><img src="images/smallimg/smallimg2.png" class="slides" alt="Image2"><img src="images/smallimg/SmallDivider.jpg" class="dividers" alt="Divider"></li>
    					<li><img src="images/smallimg/smallimg3.png" class="slides" alt="Image3"><img src="images/smallimg/SmallDivider.jpg" class="dividers" alt="Divider"></li>
    					<li><img src="images/smallimg/smallimg4.png" class="slides" alt="Image4"></li>	
    				</ul>
    			</div>
    			<!-- Navigation Button Controls -->
    			<div id="slider-nav_1">
    				<button data-dir="prev_1">Previous</button>
    				<button data-dir="next_1" style="float:right;">Next</button>
    			</div>
    		</div>
    		
    		<!-- This is Second Slider. -->
    		<div class="gallery_2">
    			<h2>MultiImage Slider-2</h2>
    			<!-- The actual moving Slider with Slides and Dividers-->
    			<div class="slider_2">
    				<ul>
    					<li><img src="images/smallimg/smallimg1.png" class="slides" alt="Image1"><img src="images/smallimg/SmallDivider.jpg" class="dividers" alt="Divider"></li>
    					<li><img src="images/smallimg/smallimg2.png" class="slides" alt="Image2"><img src="images/smallimg/SmallDivider.jpg" class="dividers" alt="Divider"></li>
    					<li><img src="images/smallimg/smallimg3.png" class="slides" alt="Image3"><img src="images/smallimg/SmallDivider.jpg" class="dividers" alt="Divider"></li>
    					<li><img src="images/smallimg/smallimg4.png" class="slides" alt="Image4"><img src="images/smallimg/SmallDivider.jpg" class="dividers" alt="Divider"></li>
    					<li><img src="images/smallimg/smallimg1.png" class="slides" alt="Image1"><img src="images/smallimg/SmallDivider.jpg" class="dividers" alt="Divider"></li>
    					<li><img src="images/smallimg/smallimg2.png" class="slides" alt="Image2"><img src="images/smallimg/SmallDivider.jpg" class="dividers" alt="Divider"></li>
    					<li><img src="images/smallimg/smallimg3.png" class="slides" alt="Image3"><img src="images/smallimg/SmallDivider.jpg" class="dividers" alt="Divider"></li>
    					<li><img src="images/smallimg/smallimg4.png" class="slides" alt="Image4"></li>	
    				</ul>
    			</div>
    			<!-- Navigation Button Controls -->
    			<div id="slider-nav_2">
    				<button data-dir="prev_2">Previous</button>
    				<button data-dir="next_2" style="float:right;">Next</button>
    			</div>
    		</div>
    		
    		
    		<!-- Loading JavaScript Codes. -->
    		<script src="scripts/jquery-2.1.0.js"></script>
    		<script src="scripts/multiSliderScript.js"></script>
    		<script>
    			// 
    			jQuery(document).ready(function ($) {
    				// creating a container variable to hold the 'UL' elements. It uses method chaining.
    				var container_1=$('div.slider_1')
    											.css('overflow','hidden')
    											.children('ul');
    				
    				var container_2=$('div.slider_2')
    											.css('overflow','hidden')
    											.children('ul');
    				
    				/* 
    				On the event of mouse-hover, 
    					i) Change the visibility of Button Controls.
    					ii) SET/RESET the "intv" variable to switch between AutoSlider and Stop mode.
    				*/
    				$('.gallery_1').hover(function( e ){
    					$('#slider-nav_1').toggle();
    					return e.type=='mouseenter'?clearInterval(intv_1):autoSlider_1();
    				});
    				
    				$('.gallery_2').hover(function( e ){
    					$('#slider-nav_2').toggle();
    					return e.type=='mouseenter'?clearInterval(intv_2):autoSlider_2();
    				});
    				
    				// Creating the 'slider' instance which will set initial parameters for the Slider.
    				var sliderobj_1= new slider(container_1,$('#slider-nav_1'));
    				var sliderobj_2= new slider(container_2,$('#slider-nav_2'));
    				/*
    				This will trigger the 'setCurrentPos' and 'transition' methods on click of any button
    				 "data-dir" attribute associated with the button will determine the direction of sliding.
    				*/
    				sliderobj_1.nav.find('button').on('click', function(){
    					sliderobj_1.setCurrentPos($(this).data('dir'));
    					sliderobj_1.transition();
    				});
    				
    				sliderobj_2.nav.find('button').on('click', function(){
    					sliderobj_2.setCurrentPos($(this).data('dir'));
    					sliderobj_2.transition();
    				});
    				
    				// Calling autoSlider() method on Page Load.
    				autoSlider_1();
    				autoSlider_2(); 
    				
    				/* 
    				This function will initialize the interval variable which will cause execution of the inner function after every 2 seconds automatically.
    				*/
    				function autoSlider_1()
    				{
    					return intv_1 = setInterval(function(){
    						sliderobj_1.setCurrentPos('next_1');
    						sliderobj_1.transition();
    					}, 2000);
    				}
    				
    				function autoSlider_2()
    				{
    					return intv_2 = setInterval(function(){
    						sliderobj_2.setCurrentPos('next_2');
    						sliderobj_2.transition();
    					}, 2000);
    				}
    				
    			});
    		</script>
    	</body>
    </html>

    CSS代码

    multiStyle.css

    JavaScript代码

    multiSliderScript.js

    /*
    This method will initialize each slider instance.
    */
    function slider(container, nav){
    	this.container=container;
    	this.nav=nav.hide(); // This will assign 'nav' from parameters to 'nav' of current slider instance. It uses method chaining.
    	this.imgs=this.container.find('.slides'); // Returns jQuery object containing all matched elements.
        console.log('Value of this.imgs is : '+this.imgs);
    	this.width=this.imgs[0].width;
    	console.log('Value of width is : '+this.width);
    	this.imgLen=this.imgs.length; // Returns the total number of sliding elements.
    	/* 	Initialize the "current" counter. 
    		This counter keeps track of the index of current slide in the unordered list of elements. 
    		This will be used for calculating the required displacement.
    	*/
    	this.current=0; // Initialize the "current" counter.
    }
    
    // This method will apply the needed animation and displacement.
    slider.prototype.transition=function(coords){
    	this.container.animate({
    		'margin-left': coords || -(this.current*this.width+35*this.current) // First element is multiplied by Zero. The number 35 is the actual gap between two slides.
    	},500);
    };
    
    // This method will set the "current" counter to next position.
    slider.prototype.setCurrentPos=function(dir){
    	var pos=this.current;
    	console.log('Value of this.value is : '+dir);
    	// It'll check which button is pressed and accordingly increments or decrements the 'pos' variable.
    	pos+= ~~(dir=='next_1' || dir=='next_2') || -1; // You can use alternate "Math.floor()" method instead of double tilde (~~) operator.
    	this.current=(pos<0)?this.imgLen-3: pos%(this.imgLen-2);
    	console.log(this.current);
    	
    };

    多滑块输出

    注意 :如果您使用的是Chrome浏览器并且要调试脚本,则可以按[F12]键并单击“控制台”选项卡,单击按钮即可查看“当前”计数器的变化情况。

If you are having any doubt in understanding the code you can ask here through comments.

如果您对理解代码有任何疑问,可以在此处通过注释询问。

jQuery图像滑块实时演示 (jQuery Image Slider Live Demo)

You can see all the above jQuery image sliders in action by visiting below demo pages.

通过访问下面的演示页面,您可以查看上面所有的jQuery图像滑块。

  1. Simple Image Slider Demo

    简单的图像滑块演示
  2. Multi Image Slider Demo

    多图像滑块演示
  3. Multiple Slider Demo

    多滑块演示

下一步是什么? (What’s next?)

How do you feel folks? I know you want to have something better than these simple sliders. So, in the next tutorial we’ll come up with some coolest features, like Pagination and Content sliders. So let’s wait for upcoming tutorial on Creating you own Content-Slider with Pagination using CSS/JQuery.

你们感觉如何? 我知道您想拥有比这些简单的滑块更好的功能。 因此,在下一个教程中,我们将提供一些最酷的功能,例如分页内容滑块。 因此,让我们等待即将到来的有关使用CSS / JQuery使用分页创建自己的Content-Slider的教程。

NOTE: This article is submitted by Prakash Upadhyay. You can find him on Facebook.

注意 :本文由Prakash Upadhyay提交。 您可以在Facebook上找到他。

翻译自: https://www.journaldev.com/4293/jquery-image-slider-css

jquery 图像滑块

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值