直接上代码:
function findPosY (obj) { //obj为所要计算的元素,可用id或class获取
var top = 0
if (obj.offsetParent) {
do {
top += obj.offsetTop
} while (obj = obj.offsetParent)
return [top]
}
}
用处:
可用于点击后获取到相应元素,并让其滚动到顶部。如:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>滚动</title>
<style type="text/css">
.classCont div {
height: 400px;
width: 200px;
border: 1px solid #000000;
}
.hrefCont{
position: fixed;
top: 50%;
left: 230px;
}
.hrefCont div{
display: block;
width: 20px;
height: 20px;
margin-bottom: 2px;
text-align: center;
line-height: 20px;
border: 1px groove #000000;
cursor: pointer;
text-decoration: none;
}
</style>
</head>
<body>
<div class="classCont">
<div id="class1">1</div>
<div id="class2">2</div>
<div id="class3">3</div>
<div id="class4">4</div>
<div id="class5">5</div>
</div>
<div class="hrefCont">
<div data-id="#class1">1</div>
<div data-id="#class2">2</div>
<div data-id="#class3">3</div>
<div data-id="#class4">4</div>
<div data-id="#class5">5</div>
</div>
</body>
<script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
function findPosY (obj) { //obj为所要计算的元素,可用id或class获取
var top = 0
if (obj.offsetParent) {
do {
top += obj.offsetTop
} while (obj = obj.offsetParent)
return [top]
}
}
$(".hrefCont div").click(function(e) {
var targetElem = $(e.currentTarget);
var targetId = targetElem.data("id");
var obj = $("#"+targetId)[0];
var scrollHeight = findPosY(obj);
window.scrollTo(0,scrollHeight);
});
});
</script>
</html>