During mobile development, we often encounter sliding events. As we all know, sliding on mobile phones mainly relies on touch events. Recently, we have encountered two pages that have similar effects to overflow:auto. Generally, it can be achieved through css settings (although it is a bit ugly), but once the overflow:auto element responds to touch events, there will be many inconveniences. For example, a certain element in fullpage automatically slides. We can use normalScrollElements to make the element not slide to the next screen when sliding, but when the element slides to the bottom, it cannot respond to the next screen event. The same is true for sliding upwards. At this time, the touch event is needed to respond. For the convenience of encapsulation in the future, a jquery plug-in is simply encapsulated, and at the same time, we also review the jquery plug-in development and touch events;
The general idea of the plug-in is as follows: The area in the box is a parent element with a fixed width and height (set overflow:hidden), and the height of the child element is greater than that of the parent element. We change the translate value of the child element by responding to the touch event (top is also possible, but the translation efficiency is higher). Of course, during this period, we need to judge the boundary of the translate value of the child element, the maximum is 0, and the minimum is the height of the child element-parent element
ps: If you want to move the child element according to the finger, you need to write another program after releasing the finger and returning to the boundary.
Let's write the plugin step by step
The first step is to establish a safe scope
;(function($){//Insert code})(jQuery) If we need to call through the $("#id").xx() method, we need to write it like below, here fn and jquery's prototype; $.extend({exec:function(){}}) //This extension calls $.fn.simuScroll = function(option){var scrollObj=new simuScroll(this,option);return scrollObj.init();}Let's take a look at the simuScroll method in the above code. This is a constructor. It accepts two parameters. ele is the element that currently accepts touch events (generally can be set as parent element), option is the configuration parameters passed by the user, such as changing the translate element, the height of the parent element child element, extra is the height that needs to be added, the callback function executed when sliding to the top or bottom, etc.
var simuScroll = function(ele,option){this.settings = {target : ele, //Event element changeTarget:'',outerHeight : '800', //Outer Height innerHeight : '500', //InnerHeight extra: '0', //Extra distance swipeUp : null,swipeDown : null,vertical:true};//Extend the default settings through jquery.extend to obtain a brand new object this.opt = jQuery.extend({},this.settings,option); this.initNumber = this.lastNumber = this.result = 0;this.flag = false;// Calculate the distance difference between the child element and the parent element to determine the maximum sliding distance of the element this.diff = parseFloat(this.opt.innerHeight) - parseFloat(this.opt.outerHeight) + parseFloat(this.opt.extra);this.diff = this.diff < 0 ? 0 :this.diff;this.direction = '';};When extending jquery prototype, the first step is to instantiate the above constructor, and the second step directly calls the init method of the constructor. See the note below for details.
init:function(){//jquery object directly binds the touch event to obtain the event, need to obtain the event attribute of the native object//jquery object obtains pagex event.originalEvent.touches[0].pageX //dom object event.touches[0].pageX var target = this.opt.target.get(0); //If the height of the child element is greater than the parent element, execute the sliding event, otherwise execute the callback function this.flag = this.diff > 0 ? 'translate' : 'exec';/*If the element has set any of the transform, scale, skew, and rotate in transform, then we will directly set transform:translateY(10px) and overwrite the initial set attributes. So we can not only ensure the original attributes by obtaining the matrix value of the element, but also set any value*/var cssText = this.opt.changeTarget.css('-webkit-transform'); if(cssText=='none'){ //The element has not set the transform attribute this.str = this.opt.vertical ? 'translateY' : 'translateX' ;}else{this.str = cssText ;var reg = /-?/d+/.?/d*/g; //Regular expression/*Get the matrix value obtained directly by each parameter in matrix is similar to matrix(1,0,0,1,0,0) and obtained by matrix(1,0,0,1,0,0) so that we can arbitrarily modify the 5th item of a certain value array as the translateX value of the element, and the 6th item is the translateY value*/this.params = this.str.match(reg); this.matrix = this.opt.vertical ? 6 : 5 ; //Can determine the value to be modified as translateY or translateX based on the passed parameters} var _this = this;//The parent element binds the touch event, passes the event object and contexttarget.addEventListener('touchstart',function(e){_this.start(e,_this)});target.addEventListener('touchmove',function(e){_this.move(e,_this)});target.addEventListener('touchend',function(e){_this.end(e,_this)});}The touchstart method is relatively simple, and the initial value of the finger touches the screen is recorded according to the direction you need to slide.
start:function(e,context){e.preventDefault();var touches = e.touches[0];context.initNumber = context.opt.vertical ? touches.pageY : touches.pageX;},The touchmove method mainly changes the element's css attributes dynamically based on the finger sliding distance, so that the element can move with the finger
The setNumber method has only one sentence: this.params.splice(n-1,1,number) Change matrix array according to the passed parameters
move:function(e,context){e.preventDefault();var touches = e.touches[0];number = context.opt.vertical ? touches.pageY : touches.pageX;//Get the change value relative to the finger touching the screen var delta = number - context.initNumber;if(context.flag == 'translate'){ //If you need to slide context.result = context.lastNumber + delta;//Set the maximum and minimum values of sliding context.result = context.result > 0 ? 0 : context.result ;context.result = -context.result > context.diff ? -context.diff : context.result;//Dynamic setting of element css attribute if(context.matrix){switch (context.matrix) {case 6: context.setNumber(6,context.result)break; case 5:context.setNumber(5,context.result)break;}context.opt.changeTarget.css('-webkit-transform','matrix('+context.params.join(',')+')')}else{context.opt.changeTarget.css('-webkit-transform',context.str+'('+context.result+'px)')}}},touchend determines whether the callback function needs to be executed during release
end:function(e,context){e.preventDefault();var touches = e.changedTouches[0];var number = context.opt.vertical ? touches.pageY : touches.pageX,n = number - context.initNumber;//When the element's sliding distance is greater than 10 and the initial element's translation value is 0 and the callback function exists, then execute the callback function if(n>10 && context.lastNumber == 0 && context.opt.swipeDown){ context.opt.swipeDown()}else if(n<-10 && context.lastNumber == -context.diff && context.opt.swipeUp){context.opt.swipeUp();}//Set the constant to the result value to ensure multiple consecutive sliding situation.lastNumber = context.result;}Basically, a simple jQuery plugin is completed, the framework is as follows
;(function($){var a = function(m,n){//function content};a.prototype = {init:function(){},start:function(){},move:function(){},end:function(){},setNumber:function(){}}$.fn.scrol = function(o){var obj = new a(this,o);return obj.init()}})(jQuery)When called, the following is:
$(".outer").simuScroll({'outerHeight':$(".outer").height(),'innerHeight':$('.inner').height(),'changeTarget': $(".inner"),'swipeUp':function(){console.log('up')},'swipeDown':function(){console.log('down')},vertical:true})The above is the JS+CSS3 simulation overflow scrolling effect introduced to you by the editor. I hope it will be helpful to you. If you have any questions, please leave me a message and the editor will reply to you in time. Thank you very much for your support to Wulin.com website!