2017-03-04 115 views
2

我是Angular 2的新手,我正在尋找一種方法來爲移動用戶實現一個良好的標籤觸摸滑動導航,並向下滑動切換到下一個標籤視圖。在Angular 2中實施滑動導航的最佳方式是什麼?

到目前爲止,我發現了一個名爲angular2-useful-swiper的程序包,儘管我並不熱衷於使用它,因爲即使它們不在視圖中,我也會盡早初始化組件。

有誰知道一個很好的方式來實現基於Swipe的導航Angular 2嗎?任何反饋將不勝感激。 :)

回答

1

您可以使用HammerJS來實現觸摸操作,例如,您可以按照此plunker

包括hammer.js文件

<script src="https://cdnjs.cloudflare.com/ajax/libs/hammer.js/2.0.8/hammer.js"></script> 

npm install hammerjs --save 

對於hammerjs瀏覽器支持觸控,包括

<script src="http://cdn.rawgit.com/hammerjs/touchemulator/master/touch-emulator.js"></script> 
<script> 

進出口ORT在app.module.ts

import { HammerGestureConfig, HAMMER_GESTURE_CONFIG } from '@angular/platform-browser'; 

export class MyHammerConfig extends HammerGestureConfig { 
    overrides = <any>{ 
    'swipe': {velocity: 0.4, threshold: 20} // override default settings 
    } 
} 

@NgModule({ 
    imports: [BrowserModule], 
    declarations: [AppComponent], 
    bootstrap: [AppComponent], 
    providers: [{ 
    provide: HAMMER_GESTURE_CONFIG, 
    useClass: MyHammerConfig 
    }] // use our custom hammerjs config 
}) 

plunker link for example

要實現標籤angular2-material是一個良好的開端,遵循this link

+0

感謝您的支持! :) – Jonathan002

+0

感謝你,你可以請指導我如何平滑地移動我的頁面像https://app.ft.com/index_page/home使用hammerjs – kamalav

+0

我在滑動時做導航。但是,如果我導航到一頁面,其工作只有在重新加載後重新加載頁面。我可以修復這個 – kamalav

17

對於刷卡檢測這裏是一個比增加HammerJS簡單的解決方案:

在app.component.html:

<div (touchstart)="swipe($event, 'start')" (touchend)="swipe($event, 'end')"> 
    App content here 
</div> 

在app.component.ts:

private swipeCoord?: [number, number]; 
private swipeTime?: number; 

swipe(e: TouchEvent, when: string): void { 
    const coord: [number, number] = [e.changedTouches[0].pageX, e.changedTouches[0].pageY]; 
    const time = new Date().getTime(); 

    if (when === 'start') { 
    this.swipeCoord = coord; 
    this.swipeTime = time; 
    } 

    else if (when === 'end') { 
    const direction = [coord[0] - this.swipeCoord[0], coord[1] - this.swipeCoord[1]]; 
    const duration = time - this.swipeTime; 

    if (duration < 1000 //Rapid 
     && Math.abs(direction[0]) > 30) //Long enough 
     && Math.abs(direction[0]) > Math.abs(direction[1] * 3) { //Horizontal enough 
    const swipe = direction[0] < 0 ? 'next' : 'previous'; 
    //Do whatever you want with swipe 
    } 
} 

注:我試過HammerJS解決方案,但將其配置爲忽略鼠標手勢是不可能的,因爲你沒有哈默對象的直接訪問。所以選擇一些文本是強制導航到下一頁...

+3

這是怪胎真棒!謝謝 – dockleryxk

+1

這真的很棒。感謝分享!對我來說,它不夠水平。我決定修改水平條件(Math.abs(direction [1] * 3)

+1

好主意@PierreChavaroche我相應地修改了代碼! – pikiou

相關問題