代码之家  ›  专栏  ›  技术社区  ›  Jordan Lewallen

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

  •  0
  • Jordan Lewallen  · 技术社区  · 5 年前

    我需要开发一个switch语句,以便在鼠标事件拖动页面的某一部分(类似于页面上的断点)时运行方法。例如,当用户单击一个项目并拖动它时 1/12 屏幕的宽度, 我需要运行一次函数 ,但如果他们一直拖到 2/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 可观察的,跟踪鼠标拖动距离并将其转换为用户在页面上拖动光标的百分比距离。

    例如,当用户拖动时, 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;
    

    总结

    我想动态创建 将触发函数的语句 一次

    有没有更简单的方法来完成这项任务?这也很有用,因为用户可以将网格大小更改为他们想要的任何内容(8列而不是12列),所以 声明应该只有8个案例而不是12个。谢谢!

    2 回复  |  直到 5 年前
        1
  •  1
  •   CertainPerformance    5 年前

    不使用 switch 在这种情况下,它相当冗长而且容易出错。相反,使用数学来识别 (0.083 * NUM) 因素:

    const draggedColumns = Math.ceil(Math.abs(percentDragged) / 0.083);
    if (gridState !== draggedColumns) {
      this.resizeDragColumns(...)
      gridState = draggedColumns;
    }
    
        2
  •  0
  •   JCOC611    5 年前

    有点基于意见,但我会这样做。我不认为 switch 是正确的方法,因为是指用于静态和固定数量的情况。

    let colDragged = Math.ceil(Math.abs(percentDragged) / 0.083);
    if (gridState != colDragged ) {
        this.resizeDragColumns(...)
        gridState = colDragged ;
    }