Home  >  Article  >  Web Front-end  >  Javascript中找到子元素在父元素内相对位置的代码_javascript技巧

Javascript中找到子元素在父元素内相对位置的代码_javascript技巧

WBOY
WBOYOriginal
2016-05-16 17:51:481244browse

经过自己一晚上尝试,貌似找到了一个方法。
现在脑袋还糊涂,先记下来,以后再分析。

复制代码 代码如下:

// 找到子元素在父元素中的相对位置
function getElementTop(element){
var el = (typeof element == "string") ? document.getElementById(element) : element;
if (el.parentNode === null || el.style.display == 'none') {
return false;
}
return el.offsetTop - el.parentNode.offsetTop;
}

这个函数可以获取子元素在父元素中的相对高度,可以通过设置父元素的 scrollTop 的属性来定位到子元素的位置
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn