如何从左向右滑动 Ionic 列表项? [英] How to swipe from left to right Ionic list item?

查看:28
本文介绍了如何从左向右滑动 Ionic 列表项?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想向两侧滑动 Ionic 列表项.(即左右和左右).它非常适合左右滑动,但我无法将列表项滑动到左侧.

我使用 $ionicGesture 进行左右滑动,当我使用 swiperight 事件时,它还给我一个警报:event($ionicGesture.on('swiperight', scope.reportEvent, elem)) ,但我不能让它在左侧显示 ion-option-button.

这是我的指令和控制器代码:

.directive('onSwipeRight', function($ionicGesture) {返回 {限制:'A',链接:函数(范围,元素,属性){var 手势类型 = attrs.gestureType;开关(手势类型){案例'swipeRight':$ionicGesture.on('swiperight', scope.reportEvent, elem);休息;案例'向左滑动':$ionicGesture.on('swipeleft', scope.reportEvent, elem);休息;案例双击":$ionicGesture.on('doubletap', scope.reportEvent, elem);休息;案例点击":$ionicGesture.on('tap', scope.reportEvent, elem);休息;}}}}).controller('ChatsCtrl', function($scope, Chats) {//使用 Ionic 中的新视图缓存,仅调用控制器//当它们被重新创建或在应用程序启动时,而不是每个页面更改.//监听此页面何时处于活动状态(例如,刷新数据),//监听 $ionicView.enter 事件:////$scope.$on('$ionicView.enter', function(e) {//});$scope.chats = Chats.all();$scope.remove = 函数(聊天){Chats.remove(chat);}$scope.reportEvent = 函数(事件){警报(嗨");console.log('报告:' + event.type);event.preventDefault();};})

这是我的 html 代码.

<离子含量><ion-list can-swipe="true"><ion-itemgesture-type="swipeRight" on-swipe-right="swipeRight()" class="item-remove-animate item-avatar item-icon-right" ng-repeat="chat in chats" type="item-text-wrap" href="#/tab/chats/{{chat.id}}"><img ng-src="{{chat.face}}"><h2>{{chat.name}}</h2><p>{{chat.lastText}}</p><i class="icon ion-chevron-right icon-accessory"></i><ion-option-button class="button-assertive" ng-click="share(item)" side="left">分享</ion-option-button><ion-option-button class="button-assertive" ng-click="remove(chat)" side="right">删除</ion-option-button></ion-item></ion-list></离子含量></ion-view>

所以我想在左侧显示分享按钮,在右侧显示删除按钮.

有人可以为我提供具体的解决方案吗?

解决方案

我已经编辑了 ionic lib 来做类似的事情.但是我不能做 JSFiddle 或 Code Pen 我会给你我修改过的 ionic.css 和 ionic.bundle.js 的链接!

TL;博士

https://github./847f044d2ef2a05101ce/raw/2274365384f5eed3e4538b269f3a7d7998eb22ed/ionic.css

用你的替换它,开始一个空白的离子项目.并将此 HTML 放入其中:

 <离子窗格><ion-header-bar class="bar-stable"><h1 class="title">Ionic Blank Starter</h1></ion-header-bar><离子含量><ion-list show-delete="false" can-swipe="true" swipe-direction="both"><ion-item href="#">第 1 项<ion-option-button side="right" class="button-light icon ion-heart"></ion-option-button><ion-option-button side="right" class="button-light icon ion-email"></ion-option-button><ion-option-button side="left" class="button-assertive icon ion-trash-a"></ion-option-button></ion-item><ion-item href="#">第 2 项<ion-option-button class="button-light icon ion-heart"></ion-option-button><ion-option-button class="button-light icon ion-email"></ion-option-button><ion-option-button class="button-assertive icon ion-trash-a"></ion-option-button></ion-item></ion-list></离子含量></ion-pane>

您可以使用向左、向右或两者来指定划像方向.在 ion-options-button 中,你可以给它一个侧面.

希望能帮到你,有什么需要就问吧!稍后我会尝试在代码中评论我的更改!

我会试着解释我做了什么.

先把ionOptionButton指令改成div为按钮,一左一右

//为左侧按钮添加了第二个 div,类 item-options-leftvar ITEM_TPL_OPTION_BUTTONS ='<div class="item-options invisible">'+'</div>'+ '

为 ionic.css 文件中的左侧按钮添加 CSS

.item-options-left {位置:绝对;顶部:0;左:0;z-索引:1;高度:100%;}.item-options-left .button {高度:100%;边界:无;边界半径:0;显示:-webkit-inline-box;显示:-webkit-inline-flex;显示:-moz-inline-flex;显示:-ms-inline-flexbox;显示:inline-flex;-webkit-box-align:居中;-ms-flex-align:居中;-webkit-align-items:居中;-moz-align-items:居中;对齐项目:居中;}.item-options .button:before {边距:0 自动;}

现在更改离子列表控制器以接受滑动方向属性

.controller('$ionicList', ['$范围','$attrs','$ionicListDelegate','$ionicHistory',函数($scope,$attrs,$ionicListDelegate,$ionicHistory){var self = this;//[NEW] 带有can-swipe attr和swipe-direction side attr的对象,默认方向是左var 滑动 = {isSwipeable: 真,侧:'左'};var isReorderShown = false;var isDeleteShown = false;var deregisterInstance = $ionicListDelegate._registerInstance(自我,$attrs.delegateHandle,功能 () {返回 $ionicHistory.isActiveScope($scope);});$scope.$on('$destroy', deregisterInstance);self.showReorder = 函数(显示){如果(参数.长度){isReorderShown = !!show;}return isReorderShown;};self.showDelete = 函数(显示){如果(参数.长度){isDeleteShown = !!show;}返回 isDeleteShown;};//[NEW] 获取滑动方向属性并将其存储在一个变量中以便在其他函数中访问self.canSwipeItems = 功能(可以){如果(参数.长度){swipe.isSwipeable = !!can;swipe.side = $attrs.swipeDirection;}返回滑动;};self.closeOptionButtons = function () {self.listView &&self.listView.clearDragEffects();};}]);

最后,你应该用这个替换slideDrag函数,只需在ionic.bundle.js中搜索它

//[NEW] 将此变量添加到函数中的其他变量var ITEM_OPTIONS_CLASS_RIGHT = 'item-options-left';var SlideDrag = 函数(选择){this.dragThresholdX = opts.dragThresholdX ||10;this.el = opts.el;this.item = opts.item;this.canSwipe = opts.canSwipe;};SlideDrag.prototype = new DragOp();SlideDrag.prototype.start = 函数 (e) {var 内容、buttonsLeft、buttonsRight、offsetX、buttonsLeftWidth、buttonsRightWidth;如果 (!this.canSwipe().isSwipeable) {返回;}如果(e.target.classList.contains(ITEM_CONTENT_CLASS)){内容 = e.target;} else if (e.target.classList.contains(ITEM_CLASS)) {content = e.target.querySelector('.' + ITEM_CONTENT_CLASS);} 别的 {content = ionic.DomUtil.getParentWithClass(e.target, ITEM_CONTENT_CLASS);}//如果我们的孩子(或我们自己)没有内容区域,请跳过如果(!内容){返回;}//确保我们在滑动时没有动画content.classList.remove(ITEM_SLIDING_CLASS);//抓取物品的起始 X 点(例如,这样我们就可以判断它是打开还是关闭开始)offsetX = parseFloat(content.style[ionic.CSS.TRANSFORM].replace('translate3d(', '').split(',')[0]) || 0;//抓住按钮buttonLeft = content.parentNode.querySelector('.' + ITEM_OPTIONS_CLASS);如果(!buttonsLeft){返回;}//[新] 获取右键按钮buttonRight = content.parentNode.querySelector('.' + ITEM_OPTIONS_CLASS_RIGHT);如果(!buttonsRight){返回;}//[NEW] 在两侧添加了相同的功能,使按钮在拖动时可见if(e.gesture.direction === "left")buttonLeft.classList.remove('invisible');别的buttonRight.classList.remove('invisible');//[NEW] 为 currentDrag 添加了 buttonRight 和 buttonLeft 属性buttonLeftWidth = buttonsLeft.offsetWidth;buttonRightWidth = buttonRight.offsetWidth;this._currentDrag = {按钮左:按钮左,按钮右:按钮右,按钮左宽度:按钮左宽度,按钮右宽度:按钮右宽度,内容:内容,startOffsetX: 偏移X};};/*** 检查这是否与之前拖动的项目相同.*/SlideDrag.prototype.isSameItem = 函数(操作){如果(op._lastDrag && this._currentDrag){返回 this._currentDrag.content == op._lastDrag.content;}返回假;};SlideDrag.prototype.clean = 函数 (isInstant) {var lastDrag = this._lastDrag;if (!lastDrag || !lastDrag.content) 返回;lastDrag.content.style[ionic.CSS.TRANSITION] = '';lastDrag.content.style[ionic.CSS.TRANSFORM] = '';如果(是即时的){lastDrag.content.style[ionic.CSS.TRANSITION] = 'none';使不可见();ionic.requestAnimationFrame(function () {lastDrag.content.style[ionic.CSS.TRANSITION] = '';});} 别的 {ionic.requestAnimationFrame(function () {setTimeout(makeInvisible, 250);});}函数 makeInvisible() {lastDrag.buttonsLeft &&lastDrag.buttonsLeft.classList.add('invisible');lastDrag.buttonsRight &&lastDrag.buttonsRight.classList.add('invisible');}};SlideDrag.prototype.drag = ionic.animationFrameThrottle(function (e) {var buttonLeftWidth;var buttonRightWidth;//我们真的没有拖如果(!this._currentDrag){返回;}//检查我们是否应该开始拖动.检查我们是否拖过门槛,//或者我们从打开状态开始.如果 (!this._isDragging &&((Math.abs(e.gesture.deltaX) > this.dragThresholdX) ||(Math.abs(this._currentDrag.startOffsetX) > 0))) {this._isDragging = true;}如果(this._isDragging){buttonLeftWidth = this._currentDrag.buttonsLeftWidth;buttonRightWidth = this._currentDrag.buttonsRightWidth;//抓取新的 X 点,将其限制为零//[NEW] 添加了向右滑动新位置if (this.canSwipe().side === 'left' || (this.canSwipe().side === 'both' && e.gesture.direction === 'left'))var newX = Math.min(0, this._currentDrag.startOffsetX + e.gesture.deltaX);else if (this.canSwipe().side === 'right' || (this.canSwipe().side === 'both' && e.gesture.direction === 'right'))var newX = Math.max(0, this._currentDrag.startOffsetX + e.gesture.deltaX);var buttonWidth = 0;if (e.gesture.direction === 'right')按钮宽度 = 按钮右宽度;别的按钮宽度 = 按钮左宽度;//如果新的 X 位置超过了按钮,我们需要减慢拖动速度(橡皮筋样式)if (newX < -buttonsWidth) {//计算新的 X 位置,上限为按钮顶部newX = Math.min(-buttonsWidth, -buttonsWidth + (((e.gesture.deltaX + buttonsWidth) * 0.4)));}this._currentDrag.content.$$ionicOptionsOpen = newX !== 0;this._currentDrag.content.style[ionic.CSS.TRANSFORM] = 'translate3d(' + newX + 'px, 0, 0)';this._currentDrag.content.style[ionic.CSS.TRANSITION] = 'none';}});SlideDrag.prototype.end = function (e, doneCallback) {var self = this;//没有拖拽,直接结束如果(!self._currentDrag){doneCallback &&doneCallback();返回;}//如果我们当前正在拖动,我们想要弹回原位//最后的静止点 X 将是暴露按钮的宽度var 休息点;if (e.gesture.direction === 'left' && (this.canSwipe().side === 'left' || this.canSwipe().side === 'both'))restingPoint = -self._currentDrag.buttonsLeftWidth;if (e.gesture.direction === 'right' && (this.canSwipe().side === 'right' || this.canSwipe().side === 'both'))restingPoint = self._currentDrag.buttonsRightWidth;//检查拖动是否没有清除按钮中点//而且我们的移动速度不够快,无法打开var buttonWidth = 0;if (e.gesture.direction === 'right')buttonWidth = self._currentDrag.buttonsRightWidth;别的buttonWidth = self._currentDrag.buttonsLeftWidth;if (e.gesture.deltaX > -(buttonsWidth/2)) {//如果我们向左或向右走但速度太慢,或向右走,就回去休息if ((e.gesture.direction == "left" || e.gesture.direction == "right") && Math.abs(e.gesture.velocityX) <0.3) {休息点 = 0;}}ionic.requestAnimationFrame(function () {如果(休息点 === 0){self._currentDrag.content.style[ionic.CSS.TRANSFORM] = '';var buttonsLeft = self._currentDrag.buttonsLeft;var buttonRight = self._currentDrag.buttonsRight;设置超时(函数(){按钮左&&buttonLeft.classList.add('invisible');按钮右&&buttonRight.classList.add('invisible');}, 250);} 别的 {self._currentDrag.content.style[ionic.CSS.TRANSFORM] = 'translate3d(' + restingPoint + 'px,0,0)';}self._currentDrag.content.style[ionic.CSS.TRANSITION] = '';//杀死当前拖动如果(!self._lastDrag){self._lastDrag = {};}ionic.extend(self._lastDrag, self._currentDrag);如果(self._currentDrag){self._currentDrag.buttons = null;self._currentDrag.content = null;}self._currentDrag = null;//我们完成了,通知调用者doneCallback &&doneCallback();});};

我的解决方案并不完美,但它有效.还有其他方法可以做到这一点,我这样做是为了更好地了解 Ionic 的工作原理以及它们如何执行 Ionic 指令.

欢迎提供任何反馈,您可以尝试自己制作或改进此反馈.

I want to swipe Ionic list items to both sides. (i.e left-right AND right-left). It works perfectly for right-left swipe but I am not able to swipe list item to left side.

I used $ionicGesture for left-right swipe, and it also gives me an alert when i use swiperight event: event($ionicGesture.on('swiperight', scope.reportEvent, elem)), but I am not able to let it show the ion-option-button at the left side.

Here is my directive and controller code:

.directive('onSwipeRight', function($ionicGesture) {
  return {
    restrict :  'A',
    link : function(scope, elem, attrs) {
      var gestureType = attrs.gestureType;
      switch(gestureType) {
        case 'swipeRight':
          $ionicGesture.on('swiperight', scope.reportEvent, elem);
          break;
        case 'swipeleft':
          $ionicGesture.on('swipeleft', scope.reportEvent, elem);
          break;
        case 'doubletap':
          $ionicGesture.on('doubletap', scope.reportEvent, elem);
          break;
        case 'tap':
          $ionicGesture.on('tap', scope.reportEvent, elem);
          break;
      }

    }
  }
})

.controller('ChatsCtrl', function($scope, Chats) {
  // With the new view caching in Ionic, Controllers are only called
  // when they are recreated or on app start, instead of every page change.
  // To listen for when this page is active (for example, to refresh data),
  // listen for the $ionicView.enter event:
  //
  //$scope.$on('$ionicView.enter', function(e) {
  //});

  $scope.chats = Chats.all();
  $scope.remove = function(chat) {
    Chats.remove(chat);
  }

  $scope.reportEvent = function (event) {
    alert("hi");
    console.log('Reporting : ' + event.type);
    event.preventDefault();
};

})

Here is my html code.

<ion-view view-title="Chats">
    <ion-content>
        <ion-list can-swipe="true">
            <ion-item gesture-type="swipeRight" on-swipe-right="swipeRight()" class="item-remove-animate item-avatar item-icon-right" ng-repeat="chat in chats" type="item-text-wrap" href="#/tab/chats/{{chat.id}}">

                <img ng-src="{{chat.face}}">
                <h2>{{chat.name}}</h2>
                <p>{{chat.lastText}}</p>
                <i class="icon ion-chevron-right icon-accessory"></i>
                <ion-option-button class="button-assertive" ng-click="share(item)" side="left">
                    Share
                </ion-option-button>
                <ion-option-button class="button-assertive" ng-click="remove(chat)" side="right">
                    Delete
                </ion-option-button>
            </ion-item>
        </ion-list>
    </ion-content>
</ion-view>

So I want to display share button at left side and delete button at right side.

Can anybody provide me specific solution for it?

解决方案

I've edited ionic lib to do something like that. But i couldn't do a JSFiddle or a Code Pen i Will give you the link to my modified ionic.css and ionic.bundle.js!

TL;DR

https://gist.githubusercontent.com/booris/847f044d2ef2a05101ce/raw/2274365384f5eed3e4538b269f3a7d7998eb22ed/ionic.css

https://gist.githubusercontent.com/booris/847f044d2ef2a05101ce/raw/2274365384f5eed3e4538b269f3a7d7998eb22ed/ionic.bundle.js

Just replace it with yours, start an ionic project blank. And put this HTML in it:

 <body ng-app="starter">
       <ion-pane>
            <ion-header-bar class="bar-stable">
                <h1 class="title">Ionic Blank Starter</h1>
            </ion-header-bar>
            <ion-content>
                <ion-list show-delete="false" can-swipe="true" swipe-direction="both">
                    <ion-item href="#">
                        Item 1
                        <ion-option-button side="right" class="button-light icon ion-heart"></ion-option-button>
                        <ion-option-button side="right" class="button-light icon ion-email"></ion-option-button>
                        <ion-option-button side="left" class="button-assertive icon ion-trash-a"></ion-option-button>
                    </ion-item>
                    <ion-item href="#">
                        Item 2
                        <ion-option-button class="button-light icon ion-heart"></ion-option-button>
                        <ion-option-button class="button-light icon ion-email"></ion-option-button>
                        <ion-option-button class="button-assertive icon ion-trash-a"></ion-option-button>
                    </ion-item>
                </ion-list>
            </ion-content>
        </ion-pane>
  </body>

You can specify the wipe direction with left, right or both. And in the ion-options-button you can give it a side.

Hope it helps, anything you need just ask! I will try to comment my changes in the code later on!

EDIT: I will try to explain what i did.

First change the ionOptionButton directive to create to div for the button, one left and one right

 //added second div with class item-options-left for the left buttons

var ITEM_TPL_OPTION_BUTTONS =
        '<div class="item-options invisible">' +
        '</div>' + '<div class="item-options-left invisible">' + 
        '</div>';
IonicModule.directive('ionOptionButton', [function () {
    function stopPropagation(e) {
        e.stopPropagation();
    }
    return {
        restrict: 'E',
        require: '^ionItem',
        priority: Number.MAX_VALUE,
        compile: function ($element, $attr) {
            $attr.$set('class', ($attr['class'] || '') + ' button', true);
            return function ($scope, $element, $attr, itemCtrl) {

                if (!itemCtrl.optionsContainer) {
                    itemCtrl.optionsContainer = jqLite(ITEM_TPL_OPTION_BUTTONS);
                    itemCtrl.$element.append(itemCtrl.optionsContainer);
                }

                //[NEW] if it as an attribute side = 'left' put the button in the left container
                if ($attr.side === 'left') {
                    angular.element(itemCtrl.optionsContainer[1]).append($element);
                    itemCtrl.$element.addClass('item-left-editable');
                } else{
                    angular.element(itemCtrl.optionsContainer[0]).append($element);
                    itemCtrl.$element.addClass('item-right-editable');
                }

                //Don't bubble click up to main .item
                $element.on('click', stopPropagation);
            };
        }
    };
}]);

Add CSS to left buttons in ionic.css file

.item-options-left {
  position: absolute;
  top: 0;
  left: 0;
  z-index: 1;
  height: 100%; }
.item-options-left .button {
  height: 100%;
  border: none;
  border-radius: 0;
  display: -webkit-inline-box;
  display: -webkit-inline-flex;
  display: -moz-inline-flex;
  display: -ms-inline-flexbox;
  display: inline-flex;
  -webkit-box-align: center;
  -ms-flex-align: center;
  -webkit-align-items: center;
  -moz-align-items: center;
  align-items: center; }
.item-options .button:before {
  margin: 0 auto; }

Now change the ion-list controller to accept swipe directions attribute

.controller('$ionicList', [
  '$scope',
  '$attrs',
  '$ionicListDelegate',
  '$ionicHistory',
function ($scope, $attrs, $ionicListDelegate, $ionicHistory) {
            var self = this;

            //[NEW] object with can-swipe attr and swipe-direction side attr, default direction is left
            var swipe = {
                isSwipeable: true,
                side: 'left'
            };
            var isReorderShown = false;
            var isDeleteShown = false;

            var deregisterInstance = $ionicListDelegate._registerInstance(
                self, $attrs.delegateHandle,
                function () {
                    return $ionicHistory.isActiveScope($scope);
                }
            );
            $scope.$on('$destroy', deregisterInstance);

            self.showReorder = function (show) {
                if (arguments.length) {
                    isReorderShown = !!show;
                }
                return isReorderShown;
            };

            self.showDelete = function (show) {
                if (arguments.length) {
                    isDeleteShown = !!show;
                }
                return isDeleteShown;
            };

            //[NEW] get swipe direction attribute and store it in a variable to access in other function
            self.canSwipeItems = function (can) {
                if (arguments.length) {
                    swipe.isSwipeable = !!can;
                    swipe.side = $attrs.swipeDirection;
                }
                return swipe;
            };

            self.closeOptionButtons = function () {
                self.listView && self.listView.clearDragEffects();
            };
}]);

To end, you should replace slideDrag function with this one, just search for it in ionic.bundle.js

//[NEW] add this var to the others in the function
var ITEM_OPTIONS_CLASS_RIGHT = 'item-options-left';

var SlideDrag = function (opts) {
        this.dragThresholdX = opts.dragThresholdX || 10;
        this.el = opts.el;
        this.item = opts.item;
        this.canSwipe = opts.canSwipe;
    };

    SlideDrag.prototype = new DragOp();

    SlideDrag.prototype.start = function (e) {
        var content, buttonsLeft, buttonsRight, offsetX, buttonsLeftWidth, buttonsRightWidth;

        if (!this.canSwipe().isSwipeable) {
            return;
        }

        if (e.target.classList.contains(ITEM_CONTENT_CLASS)) {
            content = e.target;
        } else if (e.target.classList.contains(ITEM_CLASS)) {
            content = e.target.querySelector('.' + ITEM_CONTENT_CLASS);
        } else {
            content = ionic.DomUtil.getParentWithClass(e.target, ITEM_CONTENT_CLASS);
        }

        // If we don't have a content area as one of our children (or ourselves), skip
        if (!content) {
            return;
        }

        // Make sure we aren't animating as we slide
        content.classList.remove(ITEM_SLIDING_CLASS);

        // Grab the starting X point for the item (for example, so we can tell whether it is open or closed to start)
        offsetX = parseFloat(content.style[ionic.CSS.TRANSFORM].replace('translate3d(', '').split(',')[0]) || 0;

        // Grab the buttons
        buttonsLeft = content.parentNode.querySelector('.' + ITEM_OPTIONS_CLASS);
        if (!buttonsLeft) {
            return;
        }

        //[NEW] get the Right buttons
        buttonsRight = content.parentNode.querySelector('.' + ITEM_OPTIONS_CLASS_RIGHT);
        if (!buttonsRight) {
            return;
        }

        // [NEW] added the same functionality to both sides, to make buttons visible when dragged
        if(e.gesture.direction === "left")
            buttonsLeft.classList.remove('invisible');
        else
            buttonsRight.classList.remove('invisible');

        //[NEW] added buttonRight and buttonLeft properties to currentDrag

        buttonsLeftWidth = buttonsLeft.offsetWidth;
        buttonsRightWidth = buttonsRight.offsetWidth;

        this._currentDrag = {
            buttonsLeft: buttonsLeft,
            buttonsRight: buttonsRight,
            buttonsLeftWidth: buttonsLeftWidth,
            buttonsRightWidth: buttonsRightWidth,
            content: content,
            startOffsetX: offsetX
        };
    };

    /**
     * Check if this is the same item that was previously dragged.
     */
    SlideDrag.prototype.isSameItem = function (op) {
        if (op._lastDrag && this._currentDrag) {
            return this._currentDrag.content == op._lastDrag.content;
        }
        return false;
    };

    SlideDrag.prototype.clean = function (isInstant) {
        var lastDrag = this._lastDrag;

        if (!lastDrag || !lastDrag.content) return;

        lastDrag.content.style[ionic.CSS.TRANSITION] = '';
        lastDrag.content.style[ionic.CSS.TRANSFORM] = '';
        if (isInstant) {
            lastDrag.content.style[ionic.CSS.TRANSITION] = 'none';
            makeInvisible();
            ionic.requestAnimationFrame(function () {
                lastDrag.content.style[ionic.CSS.TRANSITION] = '';
            });
        } else {
            ionic.requestAnimationFrame(function () {
                setTimeout(makeInvisible, 250);
            });
        }

        function makeInvisible() {
            lastDrag.buttonsLeft && lastDrag.buttonsLeft.classList.add('invisible');
            lastDrag.buttonsRight && lastDrag.buttonsRight.classList.add('invisible');
        }
    };

    SlideDrag.prototype.drag = ionic.animationFrameThrottle(function (e) {
        var buttonsLeftWidth;
        var buttonsRightWidth;

        // We really aren't dragging
        if (!this._currentDrag) {
            return;
        }

        // Check if we should start dragging. Check if we've dragged past the threshold,
        // or we are starting from the open state.
        if (!this._isDragging &&
            ((Math.abs(e.gesture.deltaX) > this.dragThresholdX) ||
                (Math.abs(this._currentDrag.startOffsetX) > 0))) {
            this._isDragging = true;
        }

        if (this._isDragging) {
            buttonsLeftWidth = this._currentDrag.buttonsLeftWidth;
            buttonsRightWidth = this._currentDrag.buttonsRightWidth;

            // Grab the new X point, capping it at zero
            //[NEW] added right swipe new position
            if (this.canSwipe().side === 'left' || (this.canSwipe().side === 'both' && e.gesture.direction === 'left'))
                var newX = Math.min(0, this._currentDrag.startOffsetX + e.gesture.deltaX);
            else if (this.canSwipe().side === 'right' || (this.canSwipe().side === 'both' && e.gesture.direction === 'right'))
                var newX = Math.max(0, this._currentDrag.startOffsetX + e.gesture.deltaX);

            var buttonsWidth = 0;
            if (e.gesture.direction === 'right')
                buttonsWidth = buttonsRightWidth;
            else
                buttonsWidth = buttonsLeftWidth;
            // If the new X position is past the buttons, we need to slow down the drag (rubber band style) 
            if (newX < -buttonsWidth) {
                // Calculate the new X position, capped at the top of the buttons
                newX = Math.min(-buttonsWidth, -buttonsWidth + (((e.gesture.deltaX + buttonsWidth) * 0.4)));
            }



            this._currentDrag.content.$$ionicOptionsOpen = newX !== 0;

            this._currentDrag.content.style[ionic.CSS.TRANSFORM] = 'translate3d(' + newX + 'px, 0, 0)';
            this._currentDrag.content.style[ionic.CSS.TRANSITION] = 'none';
        }
    });

    SlideDrag.prototype.end = function (e, doneCallback) {
        var self = this;

        // There is no drag, just end immediately
        if (!self._currentDrag) {
            doneCallback && doneCallback();
            return;
        }

        // If we are currently dragging, we want to snap back into place
        // The final resting point X will be the width of the exposed buttons
        var restingPoint;
        if (e.gesture.direction === 'left' && (this.canSwipe().side === 'left' || this.canSwipe().side === 'both'))
            restingPoint = -self._currentDrag.buttonsLeftWidth;
        if (e.gesture.direction === 'right' && (this.canSwipe().side === 'right' || this.canSwipe().side === 'both'))
            restingPoint = self._currentDrag.buttonsRightWidth;

        // Check if the drag didn't clear the buttons mid-point
        // and we aren't moving fast enough to swipe open
        var buttonsWidth = 0;
        if (e.gesture.direction === 'right') 
            buttonsWidth = self._currentDrag.buttonsRightWidth;
        else 
            buttonsWidth = self._currentDrag.buttonsLeftWidth;
        if (e.gesture.deltaX > -(buttonsWidth / 2)) {

            // If we are going left or right but too slow, or going right, go back to resting
            if ((e.gesture.direction == "left" || e.gesture.direction == "right")  && Math.abs(e.gesture.velocityX) < 0.3) {
                restingPoint = 0;
            } 

        }

        ionic.requestAnimationFrame(function () {
            if (restingPoint === 0) {
                self._currentDrag.content.style[ionic.CSS.TRANSFORM] = '';
                var buttonsLeft = self._currentDrag.buttonsLeft;
                var buttonsRight = self._currentDrag.buttonsRight;
                setTimeout(function () {
                    buttonsLeft && buttonsLeft.classList.add('invisible');
                    buttonsRight && buttonsRight.classList.add('invisible');
                }, 250);
            } else {
                self._currentDrag.content.style[ionic.CSS.TRANSFORM] = 'translate3d(' + restingPoint + 'px,0,0)';
            }
            self._currentDrag.content.style[ionic.CSS.TRANSITION] = '';


            // Kill the current drag
            if (!self._lastDrag) {
                self._lastDrag = {};
            }
            ionic.extend(self._lastDrag, self._currentDrag);
            if (self._currentDrag) {
                self._currentDrag.buttons = null;
                self._currentDrag.content = null;
            }
            self._currentDrag = null;

            // We are done, notify caller
            doneCallback && doneCallback();
        });
    };

My solution is not perfect, but it works. and there are others ways of doing this, i did it this way to understand better how Ionic works and how they do Ionic directives.

Any feedback is welcome, and with this you can try to make your own or improve this one.

这篇关于如何从左向右滑动 Ionic 列表项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆