Math.Pow inside Math.Sqrt - 我不明白这段代码

Math.Pow inside Math.Sqrt - I don't understand this code

我正在使用我从某处获取的这段代码,用于学习目的。如果你能帮助我更好地理解它,我正在尝试对其进行分解并了解它是如何工作的。

此函数returns鼠标与相应元素之间的距离。

function calculateDistance(elem, mouseX, mouseY) {
    return Math.floor(Math.sqrt(Math.pow(mouseX - (elem.offset().left+(elem.width()/2)), 2) + Math.pow(mouseY - (elem.offset().top+(elem.height()/2)), 2)));
}

它returns一个正数,只计算鼠标和元素之间的像素。

将其剥离,只留下 Math.floor。我不知道为什么没有 math.sqrt(math.pow...) 我会根据鼠标相对于元素的位置得到负值 -> left(-x), right(x), above( -y), below(y) 元素

并为元素获取不同的中心。

function calculateDistance(elem, mouseX, mouseY) {
    return Math.floor(mouseX - (elem.offset().left+(elem.width()/2)) + mouseY - (elem.offset().top+(elem.height()/2)));
}

我知道 Math.pow 和 sqrt 自己做什么。我没有看到他们是如何找到元素的中心的,因为我认为 elem.offset().left+(elem.width()/2) 只是水平方向做的,而 elem.offset().top+(elem.height()/2) 是垂直方向做的。

勾股定理 a²+b²=c² 其中 a (x) 和 b (y) 并搜索 c(距离)

https://en.wikipedia.org/wiki/Pythagorean_theorem

I know what Math.pow and sqrt do on their own

他们正在实施 Pythagoras' theorem

I'm not seeing how they're finding the center of the element as I thought that elem.offset().left+(elem.width()/2) was doing just that horizontally meanwhile elem.offset().top+(elem.height()/2) did it vertically

这正是开发人员在这里所做的。

mouseX - (elem.offset().left+(elem.width()/2))对应联动图中的'a',elem.offset().top+(elem.height()/2)对应b

所以1

is elem.width()/2 

2

elem.height()/2 

通过添加

elem.offset().left and elem.offset().top 

你得到了元素的中心。

你得到 3

mouseX - (elem.offset().left+(elem.width()/2)

你得到 4

mouseY - (elem.offset().top+(elem.height()/2)

最后,为了找到鼠标指针和元素之间的距离,您必须使用古老的毕达哥拉斯定理 a²+b²=c²。为了找到边 34 的平方,您可以使用 Math.pow()。关于你的问题为什么当你删除它时它返回一个负整数是因为无论你平方是正数还是负数,数字的平方总是正数。例如,在这种情况下,side 3 (mouseX - (elem.offset().left+(elem.width()/2)) 的结果将为负数,因为鼠标在元素的左侧。

如果距离平方,这将为您提供长度,所以这就是为什么您需要使用 Math.sqrt 从 c² 得到 c。

最后 Math.floor 只是用来四舍五入到最接近的整数。