源代码:
下载代码
AI 编程工具
点击运行
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>菜鸟教程(runoob.com)</title> <style> #test { top: 100px; margin: 10px; padding: 10px; width: 300px; position: relative; border: 5px solid black } </style> </head> <body> <div id="test"> <p>点击按钮获取 div 元素的顶部偏移量。</p> <p><button onclick="myFunction()">点我</button></p> <p>offsetTop 为: <span id="demo"></span></p> </div> <script> function myFunction() { var testDiv = document.getElementById("test"); document.getElementById("demo").innerHTML = testDiv.offsetTop; } </script> </body> </html>
运行结果: