繁体   English   中英

如何使用 Javascript 创建具有动态案例的 Switch 语句

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM