[英]How to create a Switch statement with dynamic cases using Javascript
當鼠標事件拖動頁面的某個部分(類似於頁面上的斷點)時,我需要開發一個 switch 語句來運行一個方法。 例如,當用戶單擊一個項目並將其拖動到屏幕寬度的1/12
時,我需要運行一次 function ,但如果他們繼續拖動到屏幕寬度的2/12
,那么我需要運行function 再次。
我創建了以下 switch 語句......它有效,但我必須復制粘貼 case 語句 12 次,以解決用戶從左到右一直拖動的情況。 我選擇了 12,因為我的頁面布局使用了 css 網格,12 列作為布局:
// gridState is used to keep track of which state we are in since we only want
// to trigger the function `resizeDragColumns()` a single time, when we transition to a new breakpoint
let gridState = 0
switch(true){
// 0.083 = width ratio of a single column in a 12 column grid (e.g. 1/12 = 0.083)
case Math.abs(percentDragged) < (0.083 * 1):
if (gridState != 1) {
this.resizeDragColumns(...)
gridState = 1;
}
break;
case Math.abs(percentDragged) < (0.083 * 2):
if (gridState != 2) {
this.resizeDragColumns(...)
gridState = 2;
}
break;
....
// there are 10 more switch statements just like this
// notice how the only thing that changes is the gridState
// variable and the comparator in the case statement (e.g. 0.083 * 1, 0.083 * 2 ..)
}
此switch
語句包含在Event
observable 中,它跟蹤鼠標拖動距離並將其轉換為用戶在頁面上拖動 cursor 的百分比距離。
例如,當用戶拖動時, percentDragged
的計算方式如下:
// point.x = current X position of cursor
// mouseDownCursorPosition = X position of the cursor when the mousedown event was fired (e.g. starting x position)
// rowRef = the container the mouse is dragging within
const percentDragged = (point.x - mouseDownCursorPosition) / rowRef.getBoundingClientRect().width;
總之
我想動態創建一個switch
語句,當用戶將其 cursor 拖入頁面上的某些“斷點”時,該語句將觸發 function A SINGLE TIME 。
有沒有更簡單的方法來完成這項任務? 這也很有幫助,因為用戶可以將網格大小更改為他們想要的任何內容(8 列而不是 12 列),因此switch
語句應該只有 8 個案例而不是 12 個。謝謝!
在這種情況下不要使用switch
,它非常冗長且容易出錯。 相反,使用數學來確定(0.083 * NUM)
因子:
const draggedColumns = Math.ceil(Math.abs(percentDragged) / 0.083);
if (gridState !== draggedColumns) {
this.resizeDragColumns(...)
gridState = draggedColumns;
}
一種基於意見的方法,但這就是我的做法。 我不認為switch
是正確的方式,因為它意味着與 static 和固定數量的案例一起使用。
let colDragged = Math.ceil(Math.abs(percentDragged) / 0.083);
if (gridState != colDragged ) {
this.resizeDragColumns(...)
gridState = colDragged ;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.