Home Web Front-end JS Tutorial Introduction to the implementation of $.fn and image scrolling effects in jquery

Introduction to the implementation of $.fn and image scrolling effects in jquery

Jul 02, 2018 pm 03:08 PM
jquery how to use

This article mainly introduces the implementation of $.fn and image scrolling effects in jquery. It has a certain reference value. Now I share it with everyone. Friends in need can refer to it

Preface

I believe that the picture scrolling effect is familiar to everyone. The rendering of Bad Street is as shown below. The js implementation code is very short, but if you want to do it, you must Master the basics of jquery, IIFE, setInterval, etc. and the usage of $.fn:


Usage of $.fn in jquery

$.fn is the namespace of jquery. If you have studied the jquery source code, it is not difficult to find the following code in the source code:

jquery.fn=jquery.prototype={
 init:function(selector,context){
 /*
 *code
 */
 }
}
Copy after login

So jquery.fn is the abbreviation of jquery.prototype. The constructor jquery() instance called by our source code is actually an instance of jquery.fn.init().

The code is as follows:

jQuery = function( selector, context ) {
 //jqeruy内部使用new创建返回另一个构造函数实力是为了省去调用jquery时前面的new,并在后面定义了别名$;
 //构造函数jquery()调用的是构造函数jQuery.fn.init()的实例
 return new jQuery.fn.init( selector, context );
},/*code*/
Copy after login

After that, the subsequent code is executedjquery.fn.init.prototype =jquery.fn, use the prototype object of constructor jquery to overwrite the prototype object of jquery.fn.init() so that the jquery.fn.init instance can also be accessed jquery()’s prototype methods and properties.

How to develop plug-ins: Use $.fn to extend jquery to generate new methods.

1. You can use jquery.extend(object) to extend the jquery class itself and add new methods to the class.

2. Use jquery.fn.extend(object) to add methods to the jquery object.

Use jquery.extend(object) below to extend the jquery class and add class methods:

$.extent({ 
 add: function(a,b){
 return a+b;
 }
})
Copy after login

You can use it directly in the future$.add(1,2);//3

Usejquery.fn.extend(object)pair# below ##jquery.prototypeExpand a method.

$.fn.extend({
 [函数名]:fucntion(){
 /*code*/
 }
});
Copy after login

You can use

$("p").Function name() directly in the future.

Use $.fn in jquery to encapsulate an image scrolling plug-in

This is a plug-in that is widely used, needless to say Also know what it is. But how to implement it specifically, continue to read below. The most important part of this plug-in is the implementation of js. HTML and css are very simple and will not be described in detail. If you are already familiar with some of the following knowledge points, you can optionally skip them.

setInterval()

setInterval()You can call the function continuously according to the specified time until clearInterval is called or the window is closed.

setInterval(fucntion(){/*code*/},[time])
clearInterval(val_of_seInterval)//参数为setInterval的返回值
Copy after login

So when we make picture scrolling, when the mouse pointer is on the picture, we want to stop the picture scrolling. The setting here is very simple, just add a

on('mouseup,mouseover',fucntion(){})Event is enough;

The specific implementation code is as follows:

var time=setInterval(picTime,par.time);
/*
*code
*/
$(this).on('mouseup,mouseover',fucntion(){
 clearInterval(time);
 })
Copy after login

Ensure that the pictures can continue to scroll in a loop

When designing, we definitely don’t want the pictures to disappear after scrolling

li.length. So set a sentinel index.

var index=0;
fucntion picTime(){
 index++;
 if(index=li.length){
 index=0;
 }
 showpicture(index);
}
Copy after login

Similarly, when clicking on the previous or next picture, we also need to set a sentry so that it can continue to loop.

IIFE

You definitely want the plug-in effect to be displayed immediately when the browser is loaded after the plug-in is defined and called. Then you need to use IIFE to construct this plug-in, so as to achieve fast loading and not be interfered by other codes. Since function declaration in parentheses is invalid in js, the function enclosed by parentheses is called a function expression.


The two forms of IIFE are as follows: When parentheses appear at the end of an anonymous function and you want to call the function, it will default to the function as a function declaration. When parentheses wrap a function, it defaults to parsing the function as an expression rather than a function declaration.

(function(){}());
(function(){})();
Copy after login

Let’s first use a question from Niuke to understand IIFE:

var myObject = { 
 foo: "bar", 
 func: function() { 
 var self = this; 
 console.log(this.foo); 
 console.log(self.foo); 
 (function() { 
 console.log(this.foo); 
 console.log(self.foo); 
 }()); 
}};
 myObject.func();
Copy after login

Because this refers to the myObject object, the first one will definitely output bar, and self is the variable of this, which is equal to this, so the second one will output bar. What appears below is the first one we defined above. This is an IIFE form. At this time, the anonymous function must be executed immediately. Its this points to window, so the output is undefined. The last self is not defined in its own block-level scope, so the self of the parent scope is found upward, so the fourth The first output is still bar.

Low configuration version of picture special effects js code

Many have added comments: If you have a solid knowledge of jquery and js, it is definitely not It's hard.

//$()调用jquery对象 ,IIFE
$(function () {
 $.fn.ScrollPic = function (params) {
 //
 return this.each(function () {
 var defaults = {
 ele: '.slider',//切换对象
 Time: '2000',//自动切换时间
 speed: '1000',//图片切换速度
 scroll: true,//是否滚动图片,虽然肯定是让它滚动的,但是我们还是设置一个意思一下。
 arrow: false,//是否设置箭头
 number: true//是否添加右下角数字
 };
 //定义默认参数,其中若在html页面设置了param是,这里的params会替换defaults
 var par = $.extend({}, defaults, params);
 var scrollList = $(this).find('ul');//找到ul标签元素
 var listLi = $(this).find('li');//找到li标签元素
 var index = 0;
 var pWidth = $(this).width();
 var pHeight = $(this).height();
 var len = $(this).find("li").length;//<li>标签数量
 //设置li标签和img的宽、高
 listLi.css({ "width": pWidth, "height": pHeight });
 listLi.find(&#39;img&#39;).css({ "width": pWidth, "height": pHeight });
 //设置ul标签的宽值为li的len倍/overflow:hidden
 scrollList.css("width", pWidth * len);
 //图片循环滚动的关键所在
 function picTimer() {
 index++;
 if (index == len) { index = 0; }
 showPics(index);
 }
 //自动切换函数
 if (par.scroll)
 {
 var time = setInterval(picTimer, par.Time);
 } else {
 $(".page-btn").hide();
 }
 function showPics(index) {
 var nowLeft = -index * pWidth;
 //添加向左移动的特效
 $(this).find(scrollList).animate({ "left": nowLeft }, par.speed);
 //找到与index相等的那个按钮,添加类名current,并将每个同胞元素移除类名current
 $(this).find(paging).eq(index).addClass(&#39;current&#39;).siblings().removeClass(&#39;current&#39;);
 }
 //鼠标经过数字按钮的效果
 if (par.number) {
 $(this).append(&#39;<p class="page-btn"></p>&#39;);
 for (i = 1; i <= len; i++) {
 $(this).find(&#39;.page-btn&#39;).append(&#39;<span>&#39; + i + &#39;</span>&#39;)
 }
 var paging = $(this).find(".page-btn span");
 paging.eq(index).addClass(&#39;current&#39;);
 $(this).find(paging).on(&#39;mouseup mouseover&#39;,function (e) {
 e.preventDefault();
 //获取按钮之间的相对位置,注意这里的$(this)。
 index = $(&#39;p&#39;).find(paging).index($(this));
 showPics(index)
 });
 }
 //上一张,下一张效果
 if (par.arrow) {
 $(this).append(&#39;<span class="leftarrow"></span><span class="rightarrow"></span>&#39;)
 var prev = $(this).find(&#39;span.leftarrow&#39;);
 var next = $(this).find(&#39;span.rightarrow&#39;);
 prev.on(&#39;click&#39;,function (e){
 e.preventDefault();
 index -= 1;
 if (index == -1) { index = len - 1; }
 showPics(index);
 });//上一页
 next.on(&#39;click&#39;,function (e){
 e.preventDefault();
 index += 1;
 if (index == len) { index = 0; }
 showPics(index);
 });
 }
 //停止图片的滚动
 $(this).on(&#39;moveseup mouseover&#39;,function (e) {
 clearInterval(time);
 });
 //清除计时器
 $(this).on(&#39;mouseleave&#39;,function (e) {
 if (par.scroll) { time = setInterval(picTimer, par.Time); } else { clearInterval(time); $(this).find(&#39;$(".page-btn")&#39;).hide() }
 });
 })
}
});
Copy after login

The above is the entire content of this article. I hope it will be helpful to everyone’s study. For more related content, please pay attention to the PHP Chinese website!

Related recommendations:

jQuery realizes the draggable wishing wall effect

jQuery and canvas realize the flat throwing and color dynamics of the sphere Transformation effect

#Introduction to a simple jQuery slideshow plug-in (jquery-slider) based on JSON format data

The above is the detailed content of Introduction to the implementation of $.fn and image scrolling effects in jquery. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Detailed explanation of jQuery reference methods: Quick start guide Detailed explanation of jQuery reference methods: Quick start guide Feb 27, 2024 pm 06:45 PM

Detailed explanation of jQuery reference method: Quick start guide jQuery is a popular JavaScript library that is widely used in website development. It simplifies JavaScript programming and provides developers with rich functions and features. This article will introduce jQuery's reference method in detail and provide specific code examples to help readers get started quickly. Introducing jQuery First, we need to introduce the jQuery library into the HTML file. It can be introduced through a CDN link or downloaded

How to use PUT request method in jQuery? How to use PUT request method in jQuery? Feb 28, 2024 pm 03:12 PM

How to use PUT request method in jQuery? In jQuery, the method of sending a PUT request is similar to sending other types of requests, but you need to pay attention to some details and parameter settings. PUT requests are typically used to update resources, such as updating data in a database or updating files on the server. The following is a specific code example using the PUT request method in jQuery. First, make sure you include the jQuery library file, then you can send a PUT request via: $.ajax({u

In-depth analysis: jQuery's advantages and disadvantages In-depth analysis: jQuery's advantages and disadvantages Feb 27, 2024 pm 05:18 PM

jQuery is a fast, small, feature-rich JavaScript library widely used in front-end development. Since its release in 2006, jQuery has become one of the tools of choice for many developers, but in practical applications, it also has some advantages and disadvantages. This article will deeply analyze the advantages and disadvantages of jQuery and illustrate it with specific code examples. Advantages: 1. Concise syntax jQuery's syntax design is concise and clear, which can greatly improve the readability and writing efficiency of the code. for example,

How to remove the height attribute of an element with jQuery? How to remove the height attribute of an element with jQuery? Feb 28, 2024 am 08:39 AM

How to remove the height attribute of an element with jQuery? In front-end development, we often encounter the need to manipulate the height attributes of elements. Sometimes, we may need to dynamically change the height of an element, and sometimes we need to remove the height attribute of an element. This article will introduce how to use jQuery to remove the height attribute of an element and provide specific code examples. Before using jQuery to operate the height attribute, we first need to understand the height attribute in CSS. The height attribute is used to set the height of an element

jQuery Tips: Quickly modify the text of all a tags on the page jQuery Tips: Quickly modify the text of all a tags on the page Feb 28, 2024 pm 09:06 PM

Title: jQuery Tips: Quickly modify the text of all a tags on the page In web development, we often need to modify and operate elements on the page. When using jQuery, sometimes you need to modify the text content of all a tags in the page at once, which can save time and energy. The following will introduce how to use jQuery to quickly modify the text of all a tags on the page, and give specific code examples. First, we need to introduce the jQuery library file and ensure that the following code is introduced into the page: &lt

Use jQuery to modify the text content of all a tags Use jQuery to modify the text content of all a tags Feb 28, 2024 pm 05:42 PM

Title: Use jQuery to modify the text content of all a tags. jQuery is a popular JavaScript library that is widely used to handle DOM operations. In web development, we often encounter the need to modify the text content of the link tag (a tag) on ​​the page. This article will explain how to use jQuery to achieve this goal, and provide specific code examples. First, we need to introduce the jQuery library into the page. Add the following code in the HTML file:

Understand the role and application scenarios of eq in jQuery Understand the role and application scenarios of eq in jQuery Feb 28, 2024 pm 01:15 PM

jQuery is a popular JavaScript library that is widely used to handle DOM manipulation and event handling in web pages. In jQuery, the eq() method is used to select elements at a specified index position. The specific usage and application scenarios are as follows. In jQuery, the eq() method selects the element at a specified index position. Index positions start counting from 0, i.e. the index of the first element is 0, the index of the second element is 1, and so on. The syntax of the eq() method is as follows: $("s

How to tell if a jQuery element has a specific attribute? How to tell if a jQuery element has a specific attribute? Feb 29, 2024 am 09:03 AM

How to tell if a jQuery element has a specific attribute? When using jQuery to operate DOM elements, you often encounter situations where you need to determine whether an element has a specific attribute. In this case, we can easily implement this function with the help of the methods provided by jQuery. The following will introduce two commonly used methods to determine whether a jQuery element has specific attributes, and attach specific code examples. Method 1: Use the attr() method and typeof operator // to determine whether the element has a specific attribute

See all articles