Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/441.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用Javascript创建带有动态案例的Switch语句_Javascript - Fatal编程技术网

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

如何使用Javascript创建带有动态案例的Switch语句,javascript,Javascript,我需要开发一个switch语句,以便在鼠标事件拖动页面的某个部分(类似于页面上的断点)时运行一个方法。例如,当用户单击某个项目并将其拖动到屏幕宽度的1/12时,我需要运行一次功能,但如果他们继续拖动到屏幕宽度的2/12,则我需要再次运行该功能 我创建了下面的switch语句…它可以工作,但我必须复制粘贴case语句12次,以说明用户将从左向右拖动的情况。我选择12,因为我的页面布局使用12列css网格作为布局: // gridState is used to keep track of whic

我需要开发一个switch语句,以便在鼠标事件拖动页面的某个部分(类似于页面上的断点)时运行一个方法。例如,当用户单击某个项目并将其拖动到屏幕宽度的
1/12
时,我需要运行一次功能,但如果他们继续拖动到屏幕宽度的
2/12
,则我需要再次运行该功能

我创建了下面的switch语句…它可以工作,但我必须复制粘贴case语句12次,以说明用户将从左向右拖动的情况。我选择12,因为我的页面布局使用12列css网格作为布局:

// 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
语句,当用户将光标拖动到页面上的某些“断点”时,该语句将触发函数


有没有更简单的方法来完成这项任务?这也会有帮助,因为用户可以将网格大小更改为他们想要的任何大小(8列而不是12列),因此
switch
语句应该只有8个大小写,而不是12个大小写。谢谢

不要使用
开关
在这种情况下,它非常冗长且容易出错。相反,使用数学来确定
(0.083*NUM)
系数:

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

这是一种基于观点的观点,但我会这样做。我认为
开关
不是正确的方法,因为它用于静态和固定数量的案例

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