如何从网页代码中看出一个元素到浏览器顶端的距离
1个回答
展开全部
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<style>
body{
margin: 0;
padding: 0;
}
.mdiv{
width: 100px;
height: 100px;
background-color: #097df3;
}
</style>
</head>
<body>
<div style="height: 1000px"></div>
<div class="mdiv"></div>
<script src="jquery-2.1.1.min.js"></script>
<script>
//原生
//获取div距离顶部的距离
var mTop = document.getElementsByClassName('mdiv')[0].offsetTop;
//减去滚动条的高度
var sTop = document.body.scrollTop;
var result = mTop - sTop;
console.log(result);
//Jquery
mTop = $('.mdiv')[0].offsetTop;
sTop = $(window).scrollTop();
result = mTop - sTop;
console.log(result);
</script>
<html lang="en">
<head>
<meta charset="UTF-8">
<style>
body{
margin: 0;
padding: 0;
}
.mdiv{
width: 100px;
height: 100px;
background-color: #097df3;
}
</style>
</head>
<body>
<div style="height: 1000px"></div>
<div class="mdiv"></div>
<script src="jquery-2.1.1.min.js"></script>
<script>
//原生
//获取div距离顶部的距离
var mTop = document.getElementsByClassName('mdiv')[0].offsetTop;
//减去滚动条的高度
var sTop = document.body.scrollTop;
var result = mTop - sTop;
console.log(result);
//Jquery
mTop = $('.mdiv')[0].offsetTop;
sTop = $(window).scrollTop();
result = mTop - sTop;
console.log(result);
</script>
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询