Home > Web Front-end > H5 Tutorial > Detailed introduction on how to use H5 to implement the touch screen version of the carousel

Detailed introduction on how to use H5 to implement the touch screen version of the carousel

黄舟
Release: 2017-03-13 17:23:57
Original
1518 people have browsed it

This article mainly introduces how to use H5 to implement a touch-screen carousel. The editor thinks it is quite good, so I will share it with you now and give it as a reference. Let’s follow the editor to take a look.

I am new to the front-end and share the implementation process of the touch screen version of the carousel on the mobile phone. The general functions are as follows:

1. Support circular sliding

2. The width can be set arbitrarily, and does not need to be the same width as the screen

3. The page can be scrolled vertically

4. The callback listening element can be set to switch

5 , pure js, without any third-party library

Principle

1. Assume the width of the child element .item is 375px, use absolute positioningPlace all child elements within the parent element

2. Set the width of the parent element .carousel to 375px, which is the same width as the child element .item

3. Add touch events to the parent element .carousel: touchstart, touchmove, touchend

4. When the finger is pressed, save the initial position (clientX)

5. When the finger slides, the sliding direction is judged by the sliding distance:

① If the finger slides to the left, the current element and the element to the right of the current element will be moved at the same time

② If the finger slides to the right, then Move the current element and the element to the left of the current element at the same time

6. When the finger is lifted, use the sliding distance to determine whether to switch to the next page

①The moving distance does not exceed 50% of the width of the child element , rolls the current page back to its original position without switching the current element.

②The movement distance exceeds 50% of the width of the child element, and the current element is switched to the next element.

③Set the transform attribute of the current element to translate3d(0px, 0px, 0px), and set the z-index attribute +1

④Set the transform attribute of the next child element to translate3d(375px, 0px, 0px), and set the z-index attribute +1

⑤Set the transform attribute of the previous child element Set the attribute to translate3d(-375px, 0px, 0px), and set the z-index attribute +1

⑥Set the z-index attribute of all other child elements to the default value

7, The previous element of the first child element is the last element, and the next element of the last element is the first element. This step is implemented through a circular linked list.

When moving, the transform attribute of the child element .item is set, not the parent element .carousel

Implementation steps

html&css


//html
<p class="carousel" ontouchstart="" >  
  <p class="item" style="background: #3b76c0" >    
    <h3 >item-1</h3>  
  </p>  
  <p class="item" style="background: #58c03b;">    
    <h3>item-2</h3>  
  </p>  
  <p class="item" style="background: #c03b25;">    
    <h3>item-3</h3>
  </p> 
  <p class="item" style="background: #e0a718;">  
    <h3>item-4</h3>  
  </p>  
  <p class="item" style="background: #c03eac;">    
    <h3>item-5</h3>  
  </p>
</p>
Copy after login


//css
.carousel{
  height: 50%;
  position: relative;
  overflow: hidden;
}

.item {
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
}
Copy after login

js

Set the initial state

First implement a doubly linked list, Used to maintain elements in the carousel component.


function Node(data) {
    this.data = data;
    this.prev = null;
    this.next = null;
    this.index = -1;
}

//双向循环列表
function LinkList() {
    var _nodes = [];
    this.head = null;
    this.last = null;

    if (typeof this.append !== "function") {
        LinkList.prototype.append = function (node) {
            if (this.head == null) {
                this.head = node;
                this.last = this.head;
            }
            else {
                this.head.prev = node;
                this.last.next = node;

                node.prev = this.last;
                node.next = this.head;

                this.last = node;
            }

            node.index = _nodes.length; //务必在push前设置node.index
            _nodes.push(node);
        }
    }
}
Copy after login

After you have the linked list, create a linked list instance, add sub-elements into the linked list, and set some initial states


var _container = document.querySelector("." + containerClass);
var _items = document.querySelectorAll("." + itemClass);

var list = loop ? new LinkList() : new SingleList();
for(var i = 0; i < _items.length; i++) {
  list.append(new Node(_items[i]));
}

var _prev = null;  //保存之前显示的元素
var _current = list.head;  //保存当前显示的元素,默认为第一个元素

var _normalZIndex = _current.data.style.zIndex;  //未显示元素的z-index值
var _activeZIndex = _normalZIndex + 1;  //当前显示元素的z-index值

var _itemWidth = _current.data.offsetWidth; //子元素宽度

positionItems(); //初始化元素位置
zindexItems(_current, _activeZIndex); //将当前元素及其左右元素的z-index加1
Copy after login

Bind touch event

touchstart event

When the finger is pressed, save the initial position


_container.addEventListener("touchstart", function(e) {
  // e.preventDefault();//取消此行代码的注释会在该元素内阻止页面纵向滚动
  var touch = e.touches[0];
  startX = touch.clientX;   //保存手指按下时的位置
  startY = touch.clientY;
  _container.style.webkitTransition = ""; //取消动画效果
  startT = new Date().getTime();          //记录手指按下的开始时间
  isMove = false;
  transitionItems(_prev, false);             //取消之前元素的过渡
  transitionItems(_current, false);          //取消当前元素的过渡
}, false);
Copy after login

touchmove event

The finger slides on the screen, and the page moves with the finger


_container.addEventListener("touchmove", function(e) {
    // e.preventDefault();//取消此行代码的注释会在该元素内阻止页面纵向滚动
    var touch = e.touches[0];
    var deltaX = touch.clientX - startX;  //计算手指在X方向滑动的距离
    var deltaY = touch.clientY - startY;  //计算手指在Y方向滑动的距离
    //如果X方向上的位移大于Y方向,则认为是左右滑动
    if (Math.abs(deltaX) > Math.abs(deltaY)){
        translate = deltaX > _itemWidth ? _itemWidth : deltaX;
        translate = deltaX < -_itemWidth ? -_itemWidth : deltaX;

        //同时移动当前元素及其左右元素
        moveItems(translate); 

        isMove = true;
    }
}, false);
Copy after login

touchend event

When your finger leaves the screen, calculate which page you need to end up on


_container.addEventListener("touchend",function(e) {
    // e.preventDefault();//取消此行代码的注释会在该元素内阻止页面纵向滚动

    //是否会滚
    var isRollback = false;

    //计算手指在屏幕上停留的时间
    var deltaT = new Date().getTime() - startT;
    if (isMove) { //发生了左右滑动
        //如果停留时间小于300ms,则认为是快速滑动,无论滑动距离是多少,都停留到下一页
        if(deltaT < 300){
            translate = translate < 0 ? -_itemWidth : _itemWidth;
        }else {
            //如果滑动距离小于屏幕的50%,则退回到上一页
            if (Math.abs(translate) / _itemWidth < 0.5){
                isRollback = true;
            }else{
                //如果滑动距离大于屏幕的50%,则滑动到下一页
                translate = translate < 0 ? -_itemWidth : _itemWidth;
            }
        }

        moveTo(translate, isRollback);
    }
}, false);
Copy after login

Carousel library

For the convenience of use, I encapsulated the entire implementation process into a library and added the prev() and next() methods. It is very simple to use:


<script src="lib/carousel.js"></script>

CreateCarousel("carousel", "item", true)
  .bindTouchEvent()
  .setItemChangedHandler(onPageChanged);

//参数"carousel"为容器的类名
//参数"item"为子元素的类名
//第三个参数设置是否需要循环播放,true为循环播放
Copy after login

The above is the detailed content of Detailed introduction on how to use H5 to implement the touch screen version of the carousel. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template