jquery slider
This Article is in continuation with the tutorial on “Creating Photo-Slider using CSS and jQuery” in “Sliders” series. This will cover following topics in order:-
本文是“ 滑块 ”系列中“ 使用CSS和jQuery创建照片滑块 ”教程的续篇。 这将按顺序涵盖以下主题:
目录一目了然…… (Contents at a glance…)
- What is a Content Slider? Advantage of Content Slider. 什么是内容滑块? 内容滑块的优势。
- What is Pagination? 什么是分页?
- Pre-requisites 先决条件
- Implementing Content Sliders –
- Basic Directory Structure.
- Layout of the Content Slider.
- Explanation of jQuery prototype functions.
- Codes for Content Sliders with Pagination and Output.
- 基本目录结构。
- 内容滑块的布局。
- jQuery 原型函数的说明。
- 具有分页和输出的内容滑块的代码。
- What’s next? 下一步是什么?
什么是内容滑块? (What’s Content Slider?)
As we’ve already seen that Photo Sliders can effectively showcase the images on a limited space of a webpage. But sometime we are needed to display images having some information linked to it. For E.g., textual information, hyperlink to some other page, buttons, other embedded images etc.
正如我们已经看到的,Photo Sliders可以在网页的有限空间中有效展示图像。 但是有时候我们需要显示链接了一些信息的图像。 例如,文本信息,到其他页面的超链接,按钮,其他嵌入式图像等。
In a Content Slider, each of the slides is a DIV container element, instead of a block element like IMG. So you can add as many child element in it. The only restriction is that your contents should be within the limit of slides actual area.
在内容滑块中 ,每个幻灯片都是DIV容器元素,而不是IMG之类的块元素。 因此,您可以在其中添加尽可能多的子元素。 唯一的限制是您的内容应在幻灯片实际区域的范围内。
内容滑块比简单图像滑块的优势 (Advantage of Content Sliders over simple image sliders)
- Contents of any type can be rolled like a slide. 任何类型的内容都可以像幻灯片一样滚动。
- Textual contents can be made dynamic by directly extracting information from other Web sources. 通过直接从其他Web来源提取信息,可以使文本内容动态化。
- Hyperlink, Button, Audio, and Video etc. can be easily integrated inside a slide. 超链接,按钮,音频和视频等可以轻松地集成到幻灯片中。
- One of the application is creating an online document reader by properly integrating the slider with Back-end Database.(Seems to be quite tough! I can write a tutorial on that as well.) 该应用程序之一是通过将滑块与后端数据库正确集成来创建在线文档阅读器。(似乎很难!我也可以编写一个教程。)
- All above, Content sliders can be more interactive than trivial Images. 综上所述,“内容”滑块比“普通图像”更具互动性。
什么是分页? (What is Pagination?)
Paginations are way of indexing a list with numerals, where each index corresponds to a particular slide. One possible application of Pagination in any slider is the accessibility. At any point, you can directly navigate to a particular slide. They help in sequencing any ordered slider. Users can be guided through your slides using this sequencing mechanism.
分页是用数字索引列表的方式,其中每个索引对应于特定的幻灯片。 分页在任何滑块中的一种可能应用是可访问性。 您随时可以直接导航到特定幻灯片。 它们有助于对任何有序滑块进行排序。 使用这种排序机制,可以指导用户浏览幻灯片。
jQuery Content Slider的前提条件 (Pre-requisites for jQuery Content Slider)
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. To know more about basic jQuery functions, you can go through other jQuery tutorials posted here. Those who are familiar with these stuffs can directly start with the Implementing Content Sliders section.
本文假定读者具有有关什么是网页的基本知识,HTML基本标签,很少CSS属性以及JavaScript的专门知识。 您可以访问www.w3schools.com网站上的这些主题。 要了解有关jQuery基本功能的更多信息,您可以阅读此处发布的其他jQuery教程。 那些熟悉这些内容的人可以直接从“实施内容滑块”部分开始。
实现jQuery Content Slider (Implementing jQuery Content Slider)
Now with some basic background of HTML, CSS and JavaScript, we can proceed with the content slider implementation. Just follow the following guidelines;
现在有了HTML,CSS和JavaScript的一些基本背景,我们可以继续执行内容滑块。 只需遵循以下准则;
- Creating Directory Structure
Let’s organize different resources among folders in our Root directory.- ‘ContentPagiSlider’ 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 images used as slides background.
让我们在“根”目录中的文件夹之间组织不同的资源。- “ ContentPagiSlider”是我们的Root文件夹,其中包含带有其他子文件夹HTML文件。
- 'scripts'文件夹包含Javascript库,例如jQuery和其他一些脚本文件。
- “ styles”文件夹包含CSS文件,这些文件定义了不同HTML标记的样式。
- “图像”文件夹包含用作幻灯片背景的图像。
- Creating Layout of Content Slider
The layout of the slider is as shown in the below figure. Those who have followed the Last tutorial on Creating Simple Photo-Slider using jQuery would see some changes done in the layout of the slider. Actually we’ve added one more parent container element (Class: gallery-container) which encloses the Slider and the Pagination into a single Parent Container.
For you easiness, I’ve made the layout and pointed the different containers with colors. The dotted line border for “slider-nav” class denotes that only buttons within “slider-nav” are made visible over slides and not the “slider-nav” container.
NOTE: You can Google Chrome’s default code viewer by pressing [F12] and choosing “Elements” tab. Then hover over each element in the code to see how web page elements are highlighted.
创建内容滑块的布局滑块的布局如下图所示 。 那些遵循了使用jQuery创建简单照片滑块的上一教程的人会看到滑块布局发生了一些变化。 实际上,我们又添加了一个父容器元素( Class:gallery-container ),该元素将Slider和Pagination封装在一个父容器中。
为了方便起见,我进行了布局并用颜色指定了不同的容器。 “ slider-nav”类的虚线边框表示仅“ slider-nav”内的按钮在幻灯片上可见,而“ slider-nav ”容器不可见。
注意 :您可以通过按[F12]并选择“ 元素 ”标签来使用Google Chrome的默认代码查看器。 然后将鼠标悬停在代码中的每个元素上,以查看如何突出显示网页元素。
- Explanation of jQuery “Prototype Functions” in JS file.
- In jQuery, everything is treated like an Object. Prototype Function is a concept in jQuery, where each function is treated as an object. And each implementing slider object will have its own instance of this method (object). So here in our JavaScript file, ‘transition’ and ‘setCurrentPos’ are the two Prototype functions(i.e. objects) which can have different values for two different slider objects.
- Using this Concept of Prototype function, we can achieve re-usability of code. That is why we can have multiple sliders within a single page sharing the same code but having its own instance. That’s a very Important Concept!
slider()
method accepts three parameters and extracts some information like no. of images in the list and width of the image. It also fills the pagination container dynamically by computing the total number of slides in the UL list. For this html() jQuery method is used.- The ‘transition’ object in the JS file is for Animation purpose. It calculates the displacement at each move, and which is equal to width of the slide images. It also uses the HTML5 data attribute to identify the current slide with its corresponding pagination element, and then applies the CSS styling.
- 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.
- 在jQuery中,一切都被视为对象。 原型函数是jQuery中的一个概念,其中每个函数都被视为一个对象。 并且每个实现的滑块对象都将具有此方法的自己的实例(对象)。 因此,在我们JavaScript文件中,“ transition”和“ setCurrentPos”是两个Prototype函数(即对象),它们对于两个不同的滑块对象可以具有不同的值。
- 使用此原型概念功能,我们可以实现代码的可重用性。 这就是为什么我们可以在一个页面中有多个滑块共享同一代码但拥有自己的实例。 这是一个非常重要的概念!
-
slider()
方法接受三个参数并提取一些信息,例如no。 图片列表和图片宽度中的图片。 它还通过计算UL列表中的幻灯片总数动态填充分页容器。 为此,使用html() jQuery方法。 - JS文件中的“转换”对象用于动画目的。 它计算每次移动时的位移,该位移等于幻灯片图像的宽度。 它还使用HTML5数据属性来标识当前幻灯片及其相应的分页元素,然后应用CSS样式。
- 用户单击导航按钮后,“ setCurrentPos”对象将计算“当前”计数器的值。
- 基于按下的“下一个”或“上一个”按钮,当前值将增加或减少。 同样,如果“当前”值低于0,则将其设置为列表中的最后一个元素。
- The Content Slider Implementation( Codes )
If you have understood the layout of the slider, let’s understand a trick. One of the problem we face with these content sliders is “Long string sentences” which mostly tend to overflow the slide region. To solve this problem, we’ll be using a CSS property “word-wrap” and set its value as ‘break-word’ which makes it sure that long string words will be broken if they overflow the dedicated width and will be continued on next line.
The
ContentSlider.html
file has structural elements along with scripts related to creation of the object for our slider. Observe how each of the slide content is enlisted as the unordered list elements. Two filescontentStyle.css
andcontentSliderScript.js
contain styles and methods for controlling the slider motion, direction and also creating dynamic pagination list. 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 ‘scripts’ folder.Codes for all these files are shown below.
jQuery Content Slider HTML Code
ContentSlider.html
<!Doctype html> <html> <head> <title>Content Slider</title> <link rel="stylesheet" href="styles/contentStyle.css"> </head> <body> <!-- Container for Slider, Navigation and Pagination Controls --> <div class="gallery-container"> <div class="gallery"> <h2>Content Slider</h2> <!-- The actual moving Slider --> <div class="slider"> <ul> <li> <div class="slides"> <div class="slides_content"> <img class="bg_img" src="images/bigimg/contentimg1.jpg" alt="Image1" /> <h3> <span class="slides_heading">Page 1</span><br/> <div class="text_container"><span class="slides_texts">This is a Plain Text enclosed in a in-line tag onto a Background Image highlighted with a black background.</span> </div> </h3> </div> </div> </li> <li> <div class="slides"> <div class="slides_content"> <img class="bg_img" src="images/bigimg/contentimg2.jpg" alt="Image2" /> <h3> <span class="slides_heading">Page 2</span><br/> <div class="text_container"><span class="slides_texts">This is a Plain Text enclosed in a in-line tag onto a Background Image highlighted with a black background.</span> </div> </h3> </div> </div> </li> <li> <div class="slides"> <div class="slides_content"> <img class="bg_img" src="images/bigimg/contentimg3.jpg" alt="Image3" /> <h3> <span class="slides_heading">Page 3</span><br/> <div class="text_container"><span class="slides_texts">This is a Plain Text enclosed in a in-line tag onto a Background Image highlighted with a black background.</span> </div> </h3> </div> </div> </li> <li> <div class="slides"> <div class="slides_content"> <img class="bg_img" src="images/bigimg/contentimg4.jpg" alt="Image4" /> <h3> <span class="slides_heading">Page 4</span><br/> <div class="text_container"><span class="slides_texts">This is a Plain Text enclosed in a in-line tag onto a Background Image highlighted with a black background.</span> </div> </h3> </div> </div> </li> <li> <div class="slides"> <div class="slides_content"> <img class="bg_img" src="images/bigimg/contentimg5.jpg" alt="Image5" /> <h3> <span class="slides_heading">Page 5</span><br/> <div class="text_container"><span class="slides_texts">This is a Plain Text enclosed in a in-line tag onto a Background Image highlighted with a black background.<br/>This is a Plain Text enclosed in a in-line tag onto a Background Image highlighted with a black background.</span> </div> </h3> </div> </div> </li> <li> <div class="slides"> <div class="slides_content"> <img class="bg_img" src="images/bigimg/contentimg6.jpg" alt="Image6" /> <h3> <span class="slides_heading">Page 6</span><br/> <div class="text_container"><span class="slides_texts">This is a Plain Text enclosed in a in-line tag onto a Background Image highlighted with a black background.</span> </div> </h3> </div> </div> </li> </ul> </div> <!-- Navigation Button Controls --> <div class="slider-nav"> <button class="backbtn" data-dir="prev">Previous</button> <button class="backbtn" data-dir="next" style="float:right;">Next</button> </div> </div> <!-- Pagination Controls --> <div class="slider-pagi"> <div class="pagi-container"> <ul></ul> <!-- Here Paginations will be dynamically created, depending on Number of elements in the list. --> </div> </div> </div> <!-- Loading JavaScript Codes. --> <script src="scripts/jquery-2.1.0.js"></script> <script src="scripts/contentSliderScript.js"></script> <script> // jQuery(document).ready(function ($) { // creating a container variable to hold the 'UL' element. It uses method chaining. var container=$('div.slider') .css('overflow','hidden') .children('ul'); // creating pagination variable which holds the 'UL' element. var pagicontainer=$('div.pagi-container').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,pagicontainer,$('.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(); }); /* This will trigger the 'setCurrentPos' and 'transition' methods on click of any Pagination icons. "data-pgno" attribute associated with the Pagination icons will determine the value of current variable. */ sliderobj.pagicontainer.find('li a').on('click', function(){ sliderobj.setCurrentPos($(this).data('pgno')); 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 3 seconds automatically. */ function autoSlider() { return intv = setInterval(function(){ sliderobj.setCurrentPos('next'); sliderobj.transition(); }, 3000); } }); </script> </body> </html>
CSS Code for Content Slider
contentStyle.css
JavaScript Code for Content Slider
contentSliderScript.js
/* This method will initialize each slider instance. Parameter are: - ------------------ 1) container -> div.slider ul 2) pagicontainer -> div.pagi-container ul 3) nav -> #slider-nav */ function slider(container, pagicontainer, nav){ this.container=container; this.pagicontainer=pagicontainer; 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. // Following commented line will not work here, as DIVs are Dynamic by nature unlike images where dimensions are known at "PageLoad( )" event. // this.width=this.imgs[0].width; this.width=640; // Only add contents within this limit. Longer sentences will be continued on next Line. console.log('Value of width is : '+this.width); this.imgLen=this.imgs.length; // Returns the total number of sliding elements. console.log("Total no. of Items in the list are : "+this.imgLen); // Here we will fill the Pagination with the following list. out = ""; cnt=0; this.liArr = $(container).find('li');// Returns jQuery object containing all matched LI elements. this.liArr.each(function() { out += "<li><a href='#' data-pgno='"+cnt+"'>" + (cnt+1) + "</a></li>"; // Here (CNT+1) is displayed on the WebPage, But the "pgno" attribute starts from ZERO only. cnt++; }); this.pagicontainer.html(out); // Adding the List to the Pagination Container. this.current=0; // Initialize the "current" counter. // Apply CSS to "First" pagination element in the list. this.pagicontainer.find('li').find("[data-pgno='" + this.current + "']").css({ border : "2px solid grey", fontWeight: "900", fontSize:"18px" }); } // 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); // Remove CSS from Rest other pagination element in the list. this.pagicontainer.find('li a').css({ border : "none", fontWeight:"", fontSize:"" }); // Apply CSS to current pagination element in the list. this.pagicontainer.find('li').find("[data-pgno='" + this.current + "']").css({ border : "2px solid grey", fontWeight:"900", fontSize:"18px" }); }; // This method will set the "current" counter to next position. /* Parameters are:- --------------- 1) dir -> It can be either 'prev' or 'next' or else a number denoting slides. */ slider.prototype.setCurrentPos=function(dir){ var pos=this.current; console.log('Value of this.value is : '+dir); if(isNaN(dir)) { 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); } else this.current=Number(dir); console.log(this.current); };
The source codes have comments wherever it is needed. In case of specific doubt you can ask me directly by commenting below.
内容滑块的实现(代码)如果您了解滑块的布局,让我们了解一个技巧。 这些内容滑块面临的问题之一是“长字符串句子”,该字符串通常会溢出滑块区域。 为了解决这个问题,我们将使用CSS属性“ word-wrap”,并将其值设置为“ break-word”,这可以确保长字符串单词如果超出了专用宽度将被打破,并且将继续下一行。
ContentSlider.html
文件具有结构元素以及与为滑块创建对象有关的脚本。 观察每个幻灯片内容如何被列为无序列表元素。 两个文件contentStyle.css
和contentSliderScript.js
包含用于控制滑块运动,方向以及创建动态分页列表的样式和方法。 您还需要引用JQuery库,即https://code.jquery.com/jquery-2.1.0.js ,您可以下载并保存在“ scripts”文件夹中。所有这些文件的代码如下所示。
jQuery Content Slider HTML代码
ContentSlider.html
内容滑块CSS代码
contentStyle.css
* { margin:0; padding:0; } /* ============================== This is for Overall Styling of the Content Gallery. */ .gallery-container { border:2px solid olive; margin:10px auto; padding:0px; display:table; } .gallery { width:640px; height:370px; background:#999; /*border:2px solid green;*/ } .slider { overflow:scroll; } .slider ul { width:100000px; list-style:none; margin-left:0px; } .slider li { float:left; } /* ============================== This is for Navigation Buttons Styling. */ .slider-nav { display:none; /* This is important to hide the buttons if jQuery is Not supported. */ margin-top: -10em; cursor: pointer; } .backbtn { position:relative; } .nextbtn { position:relative; } /* ============================== This is for Pagination Styling. */ .slider-pagi { /*border:2px solid red;*/ text-align:center; /* Important : Keeps the Pagination in the center. */ width:640px; } .pagi-container { /*border: 2px solid cyan;*/ padding: 5px; display: inline-block; /* This is a good alternative for inline-flex and supports most of the browsers. */ /* display: inline-flex; */ /* This is important to remove the extra vertical spaces between 'UL' and 'pagi-container' */ } .pagi-container > ul { padding:2px; /*border:1px solid black;*/ display: inline-block; text-align: center; } .pagi-container > ul li { /* float:left; */ /* Instead write "display:inline-block" Property to set the pagi-elements in center. */ list-style:none; padding:0px; /* Setting padding as zero will increase clickable region of child('a' Anchor Element) of LI element */ border:1px solid grey; margin: 0px auto; display:inline-block; background: radial-gradient(rgba(255, 255, 255, 0.8) 50%, rgba(180,180,180,0.8)); } .pagi-container > ul li:hover { background: radial-gradient(rgba(220, 220, 220, 0.3), rgba(180,180,180,0.8) 95%); } .pagi-container > ul li a { display:inline-block; padding:5px; /* This is important to Increase the Clickable Region of the anchor Elements */ text-decoration:none; color:rgb(100,100,100); } /* ============================== This is for Styling Each of the Content Slides */ .slides { width:640px; /* This width is reduced to compensate the padding on left and right */ height:345px; /* This height is reduced to compensate the padding on top and bottom */ word-wrap:break-word; /* Avoids the Text Overflow, and breaks the long Strings/ Sentences on next line. */ background-color:rgb(198,185,221); } .slides_content { position:relative; /* Keeps the Slides Content Relative to each Slide */ width:100%; height:100%; } h3 { position:absolute; width:100%; top:50px; } h3 span.slides_texts { color: white; padding:10px; letter-spacing: 1px; background: rgba(0, 0, 0, 0.5); line-height:42px; } h3 span.slides_heading { color: white; display:table; margin:0px auto; background: rgba(0, 0, 0, 0.5); padding:10px; } h3 div.text_container { margin:10px; } .bg_img { width: 100%; height: 100%; }
内容滑块JavaScript代码
contentSliderScript.js
源代码在任何需要的地方都有注释。 如果有特殊疑问,您可以通过以下评论直接问我。
jQuery CSS滑块输出 (jQuery CSS Slider Output)
![jQuery Content Slider](https://cdn.journaldev.com/wp-content/uploads/2014/09/jQuery-Content-Slider-Output1-450x314.png)
jQuery Content Slider
jQuery内容滑块
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.
注意 :如果您使用的是Chrome浏览器并且要调试脚本,则可以按[F12]键并单击“控制台”选项卡,单击按钮即可查看“当前”计数器的变化情况。
jQuery Content Slider实时演示 (jQuery Content Slider Live Demo)
You can see this slider in action by visiting below demo page.
您可以通过访问下面的演示页面来查看此滑块的运行情况。
Content Slider with Pagination Demo
下一步是什么? (What’s next?)
Hope you’ve learnt something new and interesting. Get ready for the next article on “Image Sliders with thumbnail view of images” with pagination, vertical sliding and other effects. Happy learning!
希望您学到了一些有趣的新东西。 准备好下一篇关于“ 具有图像缩略图的图像滑块 ”的文章, 其中包括分页,垂直滑动和其他效果。 学习愉快!
NOTE: This article is submitted by Prakash Upadhyay. You can find him on Facebook.
注意:本文由Prakash Upadhyay提交。 您可以在Facebook上找到他。
翻译自: https://www.journaldev.com/4576/jquery-css-content-slider-pagination
jquery slider