搜尋
首頁web前端js教程Figma 類似於 Angular 中使用指令的輸入字段

熟悉 Figma 的人會注意到,輸入欄位支援拖曳來增加或減少值。拖曳功能非常方便,您可以透過拖曳輕鬆獲得所需的值,而不必先按一下輸入字段,然後輸入數字。

我們可以使用 Angular 指令來建構類似的東西。我們將在本實驗中使用 Angular 的所有最新功能。

Figma like input field in Angular using Directives

讓我們看看如何建造它。

我們實際上可以透過多種方式做到這一點。我們將使用指令來建構它。我們要做到這一點的方法是採用一種非常通用的方法。這樣,我們就可以重複使用邏輯來調整元素或側邊欄的大小等。

洗滌器指令 - 核心功能

輸入的主要邏輯可以被提取並封裝成指令。主要目標是監聽滑鼠事件,然後將滑鼠移動轉換為可用值。更詳細解釋:

  1. 當使用者點擊滑鼠時(mousedown 事件)。

  2. 我們開始監聽滑鼠移動(mousemove 事件)並使用該資訊將其轉換為可用值。

  3. 當使用者釋放點擊時,我們停止監聽器(mouseup 事件)。

我們將使用 rxjs 來簡化一下邏輯。

偽代碼如下圖所示。

const mousedown$ = fromEvent<mouseevent>(target, 'mousedown');
const mousemove$ = fromEvent<mouseevent>(document, 'mousemove');
const mouseup$ = fromEvent<mouseevent>(document, 'mouseup');

let startX = 0;
let step = 1;

mousedown$
  .pipe(
     tap((event) => {
       startX = event.clientX; // Initial x co-ordinate where the mouse down happened
    }),
    switchMap(() => mousemove$.pipe(takeUntil(mouseup$))))
  .subscribe((moveEvent) => {
    const delta = startX - moveEvent.clientX;
    const newValue = Math.round(startValueAtTheTimeOfDrag + delta);
  });
</mouseevent></mouseevent></mouseevent>

看看上面的程式碼,應該很清楚發生了什麼事。我們基本上儲存了初始的clientX值,也就是點擊在X軸上的位置。一旦我們有了這些訊息,當使用者移動滑鼠時,我們就可以計算初始起始位置和當前 X 位置的增量。

我們可以進一步增加更多自訂項,例如:

  1. 靈敏度 - 拖曳到最終值的距離將由靈敏度決定。靈敏度值越高,即使移動幅度不大,最終的值也會很大。

  2. 步數 - 設定移動滑鼠時的步進間隔。若步長值為 1,則最終值以 1 為步長遞增/遞減。

  3. Min - 將發出的最小值。

  4. Max - 將發出的最大值。

最終指令如下:

@Directive({
  selector: "[scrubber]",
})
export class ScrubberDirective {
  public readonly scrubberTarget = input.required<htmldivelement>({
    alias: "scrubber",
  });

  public readonly step = model<number>(1);
  public readonly min = model<number>(0);
  public readonly max = model<number>(100);
  public readonly startValue = model(0);
  public readonly sensitivity = model(0.1);

  public readonly scrubbing = output<number>();

  private isDragging = signal(false);
  private startX = signal(0);
  private readonly startValueAtTheTimeOfDrag = signal(0);
  private readonly destroyRef = inject(DestroyRef);
  private subs?: Subscription;

  constructor() {
    effect(() => {
      this.subs?.unsubscribe();
      this.subs = this.setupMouseEventListener(this.scrubberTarget());
    });

    this.destroyRef.onDestroy(() => {
      document.body.classList.remove('resizing');
      this.subs?.unsubscribe();
    });
  }

  private setupMouseEventListener(target: HTMLDivElement): Subscription {
    const mousedown$ = fromEvent<mouseevent>(target, "mousedown");
    const mousemove$ = fromEvent<mouseevent>(document, "mousemove");
    const mouseup$ = fromEvent<mouseevent>(document, "mouseup");

    return mousedown$
      .pipe(
        tap((event) => {
          this.isDragging.set(true);
          this.startX.set(event.clientX);
          this.startValueAtTheTimeOfDrag.set(this.startValue());
          document.body.classList.add("resizing");
        }),
        switchMap(() =>
          mousemove$.pipe(
            takeUntil(
              mouseup$.pipe(
                tap(() => {
                  this.isDragging.set(false);
                  document.body.classList.remove("resizing");
                })
              )
            )
          )
        )
      )
      .subscribe((moveEvent) => {
        const delta = moveEvent.clientX - this.startX();
        const deltaWithSensitivityCompensation = delta * this.sensitivity();

        const newValue =
          Math.round(
            (this.startValueAtTheTimeOfDrag() +
              deltaWithSensitivityCompensation) /
              this.step()
          ) * this.step();

        this.emitChange(newValue);
        this.startValue.set(newValue);
      });
  }

  private emitChange(newValue: number): void {
    const clampedValue = Math.min(Math.max(newValue, this.min()), this.max());
    this.scrubbing.emit(clampedValue);
  }
}
</mouseevent></mouseevent></mouseevent></number></number></number></number></htmldivelement>

如何使用清理器指令

現在我們已經準備好了指令,讓我們看看如何實際開始使用它。

const mousedown$ = fromEvent<mouseevent>(target, 'mousedown');
const mousemove$ = fromEvent<mouseevent>(document, 'mousemove');
const mouseup$ = fromEvent<mouseevent>(document, 'mouseup');

let startX = 0;
let step = 1;

mousedown$
  .pipe(
     tap((event) => {
       startX = event.clientX; // Initial x co-ordinate where the mouse down happened
    }),
    switchMap(() => mousemove$.pipe(takeUntil(mouseup$))))
  .subscribe((moveEvent) => {
    const delta = startX - moveEvent.clientX;
    const newValue = Math.round(startValueAtTheTimeOfDrag + delta);
  });
</mouseevent></mouseevent></mouseevent>

目前,我們已將scrubberTarget輸入標記為input.required,但實際上我們可以將其設為可選並自動使用指令宿主的elementRef.nativeElement,並且它的工作原理相同。如果您想將不同的元素設定為目標,scrubberTarget 將作為輸入公開。

我們還在正文中加入了一個調整大小的類,以便我們可以正確設定調整大小遊標。

@Directive({
  selector: "[scrubber]",
})
export class ScrubberDirective {
  public readonly scrubberTarget = input.required<htmldivelement>({
    alias: "scrubber",
  });

  public readonly step = model<number>(1);
  public readonly min = model<number>(0);
  public readonly max = model<number>(100);
  public readonly startValue = model(0);
  public readonly sensitivity = model(0.1);

  public readonly scrubbing = output<number>();

  private isDragging = signal(false);
  private startX = signal(0);
  private readonly startValueAtTheTimeOfDrag = signal(0);
  private readonly destroyRef = inject(DestroyRef);
  private subs?: Subscription;

  constructor() {
    effect(() => {
      this.subs?.unsubscribe();
      this.subs = this.setupMouseEventListener(this.scrubberTarget());
    });

    this.destroyRef.onDestroy(() => {
      document.body.classList.remove('resizing');
      this.subs?.unsubscribe();
    });
  }

  private setupMouseEventListener(target: HTMLDivElement): Subscription {
    const mousedown$ = fromEvent<mouseevent>(target, "mousedown");
    const mousemove$ = fromEvent<mouseevent>(document, "mousemove");
    const mouseup$ = fromEvent<mouseevent>(document, "mouseup");

    return mousedown$
      .pipe(
        tap((event) => {
          this.isDragging.set(true);
          this.startX.set(event.clientX);
          this.startValueAtTheTimeOfDrag.set(this.startValue());
          document.body.classList.add("resizing");
        }),
        switchMap(() =>
          mousemove$.pipe(
            takeUntil(
              mouseup$.pipe(
                tap(() => {
                  this.isDragging.set(false);
                  document.body.classList.remove("resizing");
                })
              )
            )
          )
        )
      )
      .subscribe((moveEvent) => {
        const delta = moveEvent.clientX - this.startX();
        const deltaWithSensitivityCompensation = delta * this.sensitivity();

        const newValue =
          Math.round(
            (this.startValueAtTheTimeOfDrag() +
              deltaWithSensitivityCompensation) /
              this.step()
          ) * this.step();

        this.emitChange(newValue);
        this.startValue.set(newValue);
      });
  }

  private emitChange(newValue: number): void {
    const clampedValue = Math.min(Math.max(newValue, this.min()), this.max());
    this.scrubbing.emit(clampedValue);
  }
}
</mouseevent></mouseevent></mouseevent></number></number></number></number></htmldivelement>

我們使用effect來啟動監聽器,這將確保當目標元素發生變化時,我們在新元素上設定監聽器。

查看實際效果

Figma like input field in Angular using Directives

我們在 Angular 中製作了一個超級簡單的 Scrubber 指令,它可以幫助我們建立類似 Figma 的輸入欄位。使用戶與數位輸入互動變得非常容易。

程式碼與演示

https://stackblitz.com/edit/figma-like-number-input-angular?file=src/scrubber.directive.ts

與我聯繫

  • 推特

  • Github

  • Linkedin

請在評論部分中添加您的想法。確保安全❤️

Figma like input field in Angular using Directives

以上是Figma 類似於 Angular 中使用指令的輸入字段的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
JavaScript數據類型:瀏覽器和nodejs之間是否有區別?JavaScript數據類型:瀏覽器和nodejs之間是否有區別?May 14, 2025 am 12:15 AM

JavaScript核心數據類型在瀏覽器和Node.js中一致,但處理方式和額外類型有所不同。 1)全局對像在瀏覽器中為window,在Node.js中為global。 2)Node.js獨有Buffer對象,用於處理二進制數據。 3)性能和時間處理在兩者間也有差異,需根據環境調整代碼。

JavaScript評論:使用//和 / * * / * / * /JavaScript評論:使用//和 / * * / * / * /May 13, 2025 pm 03:49 PM

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

Python vs. JavaScript:開發人員的比較分析Python vs. JavaScript:開發人員的比較分析May 09, 2025 am 12:22 AM

Python和JavaScript的主要區別在於類型系統和應用場景。 1.Python使用動態類型,適合科學計算和數據分析。 2.JavaScript採用弱類型,廣泛用於前端和全棧開發。兩者在異步編程和性能優化上各有優勢,選擇時應根據項目需求決定。

Python vs. JavaScript:選擇合適的工具Python vs. JavaScript:選擇合適的工具May 08, 2025 am 12:10 AM

選擇Python還是JavaScript取決於項目類型:1)數據科學和自動化任務選擇Python;2)前端和全棧開發選擇JavaScript。 Python因其在數據處理和自動化方面的強大庫而備受青睞,而JavaScript則因其在網頁交互和全棧開發中的優勢而不可或缺。

Python和JavaScript:了解每個的優勢Python和JavaScript:了解每個的優勢May 06, 2025 am 12:15 AM

Python和JavaScript各有優勢,選擇取決於項目需求和個人偏好。 1.Python易學,語法簡潔,適用於數據科學和後端開發,但執行速度較慢。 2.JavaScript在前端開發中無處不在,異步編程能力強,Node.js使其適用於全棧開發,但語法可能複雜且易出錯。

JavaScript的核心:它是在C還是C上構建的?JavaScript的核心:它是在C還是C上構建的?May 05, 2025 am 12:07 AM

javascriptisnotbuiltoncorc; sanInterpretedlanguagethatrunsonenginesoftenwritteninc.1)JavascriptwasdesignedAsignedAsalightWeight,drackendedlanguageforwebbrowsers.2)Enginesevolvedfromsimpleterterpretpretpretpretpreterterpretpretpretpretpretpretpretpretpretcompilerers,典型地,替代品。

JavaScript應用程序:從前端到後端JavaScript應用程序:從前端到後端May 04, 2025 am 12:12 AM

JavaScript可用於前端和後端開發。前端通過DOM操作增強用戶體驗,後端通過Node.js處理服務器任務。 1.前端示例:改變網頁文本內容。 2.後端示例:創建Node.js服務器。

Python vs. JavaScript:您應該學到哪種語言?Python vs. JavaScript:您應該學到哪種語言?May 03, 2025 am 12:10 AM

選擇Python還是JavaScript應基於職業發展、學習曲線和生態系統:1)職業發展:Python適合數據科學和後端開發,JavaScript適合前端和全棧開發。 2)學習曲線:Python語法簡潔,適合初學者;JavaScript語法靈活。 3)生態系統:Python有豐富的科學計算庫,JavaScript有強大的前端框架。

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser是一個安全的瀏覽器環境,安全地進行線上考試。該軟體將任何電腦變成一個安全的工作站。它控制對任何實用工具的訪問,並防止學生使用未經授權的資源。

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

強大的PHP整合開發環境

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

DVWA

DVWA

Damn Vulnerable Web App (DVWA) 是一個PHP/MySQL的Web應用程序,非常容易受到攻擊。它的主要目標是成為安全專業人員在合法環境中測試自己的技能和工具的輔助工具,幫助Web開發人員更好地理解保護網路應用程式的過程,並幫助教師/學生在課堂環境中教授/學習Web應用程式安全性。 DVWA的目標是透過簡單直接的介面練習一些最常見的Web漏洞,難度各不相同。請注意,該軟體中