javascript - 优化判别区域的函数
PHPz
PHPz 2017-04-11 11:47:04
[JavaScript讨论组]
//根据坐标位置返回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,请问如何优化这段代码?

PHPz
PHPz

学习是最好的投资!

全部回复(3)
伊谢尔伦

供参考:

function moveboxPosition(position) {
    // 算出落点在第m行,第n列
    // 每行有a列,返回 m * a + n
    return Math.floor(position.x/100) * 3 + Math.floor(position.y/100);
}
ringa_lee

假设每个区域的长宽都为size
假设每个区域的序数是按类似你上面代码的规则排列的
也就是
012
345
678
这种形式
也就是每行或每列的区域数是总区域数的平方根
那就很简单啦
位置的横坐标除以每行的区域数 应该落在 该位置所在区域的序数mod每行区域数乘以size的范围内
位置的纵坐标除以每列的区域数 应该落在 该位置所在区域的序数除以每列区域数乘以size的范围内
假设该区域序数为order,区域数为num,每行或每列区域数的平方根lineNum为Math.sqrt(num)
那么

this.scope(position.x, order % lineNum * size, (order % lineNum + 1) * size) && this.scope(position.y, Math.floor(order / lineNum * size), (Math.floor(order / lineNum) + 1) * size)

那么已知其它数,如何得到order呢? 笨点的方法就是来个循环order从0到区域数,如果scope函数返回true那就返回当前order
聪明点的方法就是逆运算

具体就不说了,留点思考的空间给你。

天蓬老师

把所有的格子的左上角和右下角的offsetLeft和offsetRight保存在数组对象里面里面[[0,0,1,1],[1,0,1,1],...],然后每次只需要遍历判断鼠标所在区域是否对应数组里的区域....

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号