$('body').offset().top总是返回8,即使页面上没有其他内容

$('body').offset().top always returns 8 even with nothing else on the page

本文关键字:其他 返回 top offset body      更新时间:2023-09-26

我以为$('body').offset().top应该返回0,但显然它一直在返回8。我从我的网页上删除了所有不必要的代码,它仍然返回8

这是我所拥有的:

<!DOCTYPE html>
<html lang="en">
    <head>
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
        <meta charset="utf-8" />
        <title></title>
    </head>
    <body>
        <script>
            $(document).ready(function () {
                console.log($('body').offset().top);
            })
        </script>
    </body>
</html>

这就是我代码中的所有内容。以下是JSFiddle:http://jsfiddle.net/Lspkx2su/

默认CSS。插入以下内容:

<style>
  html, body { margin: 0 }
</style>

然后再试一次。

默认情况下,body标记的样式会占用网页中的空间。

试试这个代码你会明白的-

HTML

<body>
<div class="wrapper">
Hello World
</div>
</body>

以及以下CSS

.wrapper{
border: 1px solid red;
}

当您运行上面的代码时,您会看到您的"Hello World"显示为带有一个小偏移。这是HTML/CSS中的默认设置。

然而,@amadan是绝对正确的。您应该始终使用以下内容来启动网页CSS。不会出现偏移问题。

body{
  margin:0;padding:0;  
  /* considering your outermost div to be the wrapper of your whole page */
}