Created
April 4, 2015 03:22
-
-
Save ishenli/e1ac08e3e8ae68738b79 to your computer and use it in GitHub Desktop.
triangle.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @file triangle 识别 | |
* @author shenli | |
* 原理可以参考:http://36kr.com/p/201751.html | |
*/ | |
var triangle = { | |
init: function (navContainer, navs) { | |
var me = this; | |
me.container = $(navContainer).eq(0); | |
if (typeof navs === 'string') { | |
me.navs = me.container.find(navs); | |
} | |
else { | |
me.navs = $(navs); | |
} | |
me.containerOffset = me.container.offset(); | |
me.containerBox = { | |
width: navContainer.width(), | |
height: navContainer.height() | |
}; | |
// 这个三角形是以左下角为做坐标轴原点,得到每个点相对于原点的坐标 | |
me.triangle = { | |
pointXY: { | |
x: me.containerBox.width, | |
y: me.containerBox.height | |
}, | |
pointX: { | |
x: me.containerBox.width, | |
y: 0 | |
}, | |
pointY: { | |
x: 0, | |
y: me.containerBox.height | |
} | |
}; | |
me.navs.on('mouseenter', function (e) { | |
// 更新三角形左侧点的坐标 | |
me.triangle.pointY = me._getVirtualCoordinate(e); | |
}); | |
}, | |
/** | |
* 判断是否在三角区域内 | |
* @param {event} e 事件对象 | |
* @return {boolean} | |
*/ | |
isInTriangle: function (e) { | |
var me = this; | |
var coordinate = me._getVirtualCoordinate(e); | |
var point2pointXYK = (me.triangle.pointXY.y - coordinate.y) / (me.triangle.pointXY.x - coordinate.x); | |
var point2pointXK = (me.triangle.pointX.y - coordinate.y) / (me.triangle.pointX.x - coordinate.x); | |
var pointX2pointYk = (me.triangle.pointX.y - me.triangle.pointY.y) / (me.triangle.pointX.x - me.triangle.pointY.x); | |
// 鼠标在导航栏右侧 | |
if (coordinate.x > me.triangle.pointXY.x) { | |
return true; | |
} | |
// 在从导航栏到左侧左边坐标点的区间内 | |
else if (coordinate.x >= me.triangle.pointY.x) { | |
if (coordinate.y >= me.triangle.pointY.y && point2pointXYK >= 0 | |
|| coordinate.y < me.triangle.pointY.y && point2pointXK < pointX2pointYk) { | |
return true; | |
} | |
} | |
return false; | |
}, | |
/** | |
* 获取鼠标点击点距离容器左下角的位移 | |
* @param {Object} e 事件对象 | |
* @return {{x: number, y: number}} | |
* @private | |
*/ | |
_getVirtualCoordinate: function (e) { | |
var me = this; | |
return { | |
x: e.pageX - me.containerOffset.left, | |
y: me.containerBox.height - (e.pageY - me.containerOffset.top) | |
}; | |
} | |
}; | |
module.exports = triangle; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment