Рубрики
Uncategorized

Как реализовать Переключение изображений со скольжением пальцев H5+CSS3

Автор оригинала: David Wong.

Он содержит три файла: html , slider-H5.js и jquery.js. Параметры скольжения можно настроить в формате html. Код выглядит следующим образом:

HTML-код:




    
    
        
        
        
        
        
        
        
        
        
            H5 finger sliding switching pictures
        
        // Welcome to join the whole stack development exchange circle to learn and exchange: 1007317281
    
                                       
    
        
  • // Welcome to join the whole stack development exchange circle to learn and exchange: 1007317281
Here, the callback shows how many pages are currently scrolled to: 0
//Welcome to join the whole stack development exchange circle to learn and exchange: 1007317281

Slider-H5.js код:

(function($) {
    /*
        Picture scrolling effect
        @ jQuery or @String box: scrolling list jQuery objects or selectors such as outer UL whose scrolling element is Li
        @object config : {
                @ Number width: The width of a scroll is defaulted to the width of the first subelement in the box [If the width of the subelement is not uniform, the scrolling effect will be confused]
                @ Number size: List length, default to the number of all first-level sub-elements in box [if size is not equal to the number of first-level sub-elements, circular scrolling is not supported]
                @ Boolean loop: Supports circular scrolling with default true
                @ Boolean auto: Whether or not to automatically scroll, support for automatic scroll must support circular scroll, otherwise the setting is invalid, the default is true
                @ Number auto_wait_time: Automatic rotation interval, default: 3000ms
                @ Function callback: The scroll-through callback function takes into account the current scroll node index value of a parameter
            }
    */
    function mggScrollImg(box, config) {
        this.box = $(box);
        this.config = $.extend({},
        config || {});
        This. width = this. config. width | | this. box. children (). EQ (0). width (); // width of a scroll
        this.size = this.config.size || this.box.children().length;
        This. loop = this. config. loop!== undefined? (this. config. loop = true? True: false): true; // default can scroll round and round
        This. auto = this. config. auto!= undefined? (this. config. auto = true? True: false): true; // default auto scroll
        This. auto_wait_time = this. config. auto_wait_time | | 3000; // rotation interval
        This. scroll_time = this. config. scroll_time!== undefined? (this. config. scroll_time > 0? This. config. scroll_time: 0): 300; //rolling time
        This. minleft = this. width * (this. size - 1); // minimum left value, note that it is a negative number [in the case of no circulation]
        This. maxleft = 0; // maximum lfet value [value without looping]
        This.now_left = 0; // Initial position information [Value without loop]
        This. point_x = null; // Record an X coordinate
        This. point_y = null; // Record a Y coordinate
        This. move_left = false; // Where does the record slide?
        this.index = 0;
        this.busy = false;
        this.timer;
        this.init();
    }// Welcome to join the whole stack development exchange circle to learn and exchange: 1007317281
    $.extend(mggScrollImg.prototype, {
        init: function() {
            this.bind_event();
            this.init_loop();
            this.auto_scroll();
        },
        bind_event: function() {
            var self = this;
            self.box.bind('touchstart',
            function(e) {
                var t = e.touches ? e.touches: e.originalEvent.targetTouches;
                if (t.length == 1 && !self.busy) {
                    self.point_x = t[0].screenX;
                    self.point_y = t[0].screenY;
                }
            }).bind('touchmove',
            function(e) {
                var t = e.touches ? e.touches: e.originalEvent.targetTouches;
                if (t.length == 1 && !self.busy) {
                    Return self. move (t [0]. screenX, t [0]. screenY); // Here, according to the return value, do you feel that the default touch event is blocked?
                }
            }).bind('touchend',
            function(e) { ! self.busy && self.move_end();
            });
        },
        /*
            Initialize cyclic scrolling. When multiple sub-elements need to be scrolled at one time, cyclic scrolling effect is not supported for the time being.
            If you want to achieve the effect of scrolling multiple sub-elements at one time, you can achieve it through the page structure.
            The idea of circular rolling: copy the beginning and end nodes to the end
        */
        init_loop: function() {
            If (this. box. children (). length > 1 & & this. box. children (). length = this. size & this. loop {// temporarily only supports cycles where size and number of child nodes are equal
                This.now_left=-this.width;//Set the initial location information
                This. minleft = this. width * this. size; // minimum left value
                this.maxleft = -this.width;
                this.box.prepend(this.box.children().eq(this.size - 1).clone()).append(this.box.children().eq(1).clone()).css(this.get_style(2));
                this.box.css('width', this.width * (this.size + 2));
            } else {
                this.loop = false;
                this.box.css('width', this.width * this.size);
            }// Welcome to join the whole stack development exchange circle to learn and exchange: 1007317281
        },
        Auto_scroll: function () {// auto scroll
            var self = this;
            if (!self.auto) return;
            clearTimeout(self.timer);
            self.timer = setTimeout(function() {
                self.go_index(self.index + 1);
            },
            self.auto_wait_time);
        },
        Go_index: function (ind) {// scroll to the specified index page
            var self = this;
            if (self.busy) return;
            clearTimeout(self.timer);
            self.busy = true;
            If (self. loop) {// If the loop
                ind = ind < 0 ? -1 : ind;
                ind = ind > self.size ? self.size: ind;
            } else {
                ind = ind < 0 ? 0 : ind;
                ind = ind >= self.size ? (self.size - 1) : ind;
            }
            if (!self.loop && (self.now_left == -(self.width * ind))) {
                self.complete(ind);
            } else if (self.loop && (self.now_left == -self.width * (ind + 1))) {
                self.complete(ind);
            } else {
                If (ind = - 1 | | ind == self. size) {// Loop Scroll Boundary
                    self.index = ind == -1 ? (self.size - 1) : 0;
                    self.now_left = ind == -1 ? 0 : -self.width * (self.size + 1);
                } else {
                    self.index = ind;
                    self.now_left = -(self.width * (self.index + (self.loop ? 1 : 0)));
                }
                self.box.css(this.get_style(1));
                setTimeout(function() {
                    self.complete(ind);
                },
                self.scroll_time);
            }
        },
        Complete: function (ind) {// animation completion callback
            var self = this;
            self.busy = false;
            self.config.callback && self.config.callback(self.index);
            if (ind == -1) {
                self.now_left = self.minleft;
            } else if (ind == self.size) {
                self.now_left = self.maxleft;
            }
            self.box.css(this.get_style(2));
            self.auto_scroll();
        },
        Next: function () {// scroll on the next page
            if (!this.busy) {
                this.go_index(this.index + 1);
            }
        },
        Prev: function () {// scroll on the previous page
            if (!this.busy) {
                this.go_index(this.index - 1);
            }// Welcome to join the whole stack development exchange circle to learn and exchange: 1007317281
        },
        Move: function (point_x, point_y) {// sliding screen handler
            var changeX = point_x - (this.point_x === null ? point_x: this.point_x),
            changeY = point_y - (this.point_y === null ? point_y: this.point_y),
            marginleft = this.now_left,
            return_value = false,
            sin = changeY / Math.sqrt(changeX * changeX + changeY * changeY);
            this.now_left = marginleft + changeX;
            this.move_left = changeX < 0;
            If (sin > Math. sin (Math. PI / 3) | | sin < - Math. sin (Math. PI / 3)) {/ sliding screen angle range: PI / 3 - 2PI / 3
                Return_value = true; // does not prevent default behavior
            }
            this.point_x = point_x;
            this.point_y = point_y;
            this.box.css(this.get_style(2));
            return return_value;
        },
        move_end: function() {
            var changeX = this.now_left % this.width,
            ind;
            If (this. now_left < this. minleft) {// slide your finger to the left
                ind = this.index + 1;
            } Other if (this. now_left > this. maxleft) {// slide your finger to the right
                ind = this.index - 1;
            } else if (changeX != 0) {
                If (this. move_left) {// slide your finger to the left
                    ind = this.index + 1;
                } else {// Slide your finger to the right
                    ind = this.index - 1;
                }
            } else {
                ind = this.index;
            }
            this.point_x = this.point_y = null;
            this.go_index(ind);
        },
        /*
            To get animation styles that are compatible with more browsers, you can extend this approach
            @ int fig: 1 animation 2 no animation
        */
        get_style: function(fig) {
            var x = this.now_left,
            time = fig == 1 ? this.scroll_time: 0;
            return {
                '-webkit-transition': '-webkit-transform ' + time + 'ms',
                '-webkit-transform': 'translate3d(' + x + 'px,0,0)',
                '-webkit-backface-visibility': 'hidden',
                'transition': 'transform ' + time + 'ms',
                'transform': 'translate3d(' + x + 'px,0,0)'
            };
        }// Welcome to join the whole stack development exchange circle to learn and exchange: 1007317281
    });
    /*
        Here, call interface is provided to the outside world, and interface method is provided to the outside world.
        Next: next page
        Prev: Last page
        Go: Scroll to the specified page
    */
    $.mggScrollImg = function(box, config) {
        var scrollImg = new mggScrollImg(box, config);
        Return {// Provide an interface to the outside world
            next: function() {
                scrollImg.next();
            },
            prev: function() {
                scrollImg.prev();
            },
            go: function(ind) {
                scrollImg.go_index(parseInt(ind) || 0);
            }
        }
    }
})(jQuery)

эпилог

Спасибо, что посмотрели. Если есть какие-либо недостатки, вы можете их критиковать и исправлять. Доступ к информации (iv), (iv) На этот раз мы рекомендуем бесплатную учебную группу, которая обобщает разработку веб-сайтов мобильных приложений, css, html, webpack, Vue node и ресурсы для интервью. Студенты, интересующиеся технологиями веб-разработки, могут присоединиться к группе Q: ???1007317281??? Независимо от того, являетесь ли вы Сяобаем или Дэниелом, я приветствую Дэниела, чтобы он организовал набор эффективных учебных маршрутов и учебных пособий, которыми можно бесплатно поделиться с вами, ежедневно обновляя видеоматериалы. Наконец, я желаю вам всем как можно скорее успехов в учебе, получить удовлетворительное предложение, получить быстрое продвижение по службе и повышение зарплаты, а также достичь вершин своей жизни.