Home  >  Article  >  Web Front-end  >  Code to find the relative position of child elements within parent elements in Javascript_javascript tips

Code to find the relative position of child elements within parent elements in Javascript_javascript tips

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

After trying it all night, I seem to have found a way.
My mind is still confused now, so write it down first and analyze it later.

Copy code The code is as follows:

// Find the relative position of the child element in the parent element
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;
}

This function can Get the relative height of the child element in the parent element. You can position the child element by setting the scrollTop attribute of the parent element.
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