//根据坐标位置返回index
Jigsaw.prototype.moveboxPosition = function(position) {
if (this.scope(position.x, 0, 100) && this.scope(position.y, 0, 100)) {
return 0
} else if (this.scope(position.x, 100, 200) && this.scope(position.y, 0, 100)) {
return 1
} else if (this.scope(position.x, 200, 300) && this.scope(position.y, 0, 100)) {
return 2
} else if (this.scope(position.x, 0, 100) && this.scope(position.y, 100, 200)) {
return 3
} else if (this.scope(position.x, 100, 200) && this.scope(position.y, 100, 200)) {
return 4
} else if (this.scope(position.x, 200, 300) && this.scope(position.y, 100, 200)) {
return 5
} else if (this.scope(position.x, 0, 100) && this.scope(position.y, 200, 300)) {
return 6
} else if (this.scope(position.x, 100, 200) && this.scope(position.y, 200, 300)) {
return 7
} else if (this.scope(position.x, 200, 300) && this.scope(position.y, 200, 300)) {
return 8
} else {
return false
}
};
//判断数值是否在给定区间
Jigsaw.prototype.scope = function(num, min, max) {
if (num >= min && num <= max) {
return true
} else {
return false
}
};
以上代码是用来判断拖拽的p落在九宫格的哪个区域,如果有100个区域,那岂不是要99个else if,请问如何优化这段代码?
Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
供参考:
假设每个区域的长宽都为size
假设每个区域的序数是按类似你上面代码的规则排列的
也就是
012
345
678
这种形式
也就是每行或每列的区域数是总区域数的平方根
那就很简单啦
位置的横坐标除以每行的区域数 应该落在 该位置所在区域的序数mod每行区域数乘以size的范围内
位置的纵坐标除以每列的区域数 应该落在 该位置所在区域的序数除以每列区域数乘以size的范围内
假设该区域序数为order,区域数为num,每行或每列区域数的平方根lineNum为Math.sqrt(num)
那么
那么已知其它数,如何得到order呢? 笨点的方法就是来个循环order从0到区域数,如果scope函数返回true那就返回当前order
聪明点的方法就是逆运算
具体就不说了,留点思考的空间给你。
把所有的格子的左上角和右下角的offsetLeft和offsetRight保存在数组对象里面里面[[0,0,1,1],[1,0,1,1],...],然后每次只需要遍历判断鼠标所在区域是否对应数组里的区域....