第六课 js管理页面元素位置大小

网页文档的大小和浏览器窗口的大小

首先,要明确两个基本概念。
一张网页的全部面积,就是它的大小。通常情况下,网页的大小由网页内容的多少和CSS样式表决定。
浏览器窗口的大小,则是指在浏览器窗口中看到的那部分网页面积,又叫做viewport(视口)。
很显然,如果网页的内容能够在浏览器窗口中全部显示(也就是不出现滚动条),那么网页的大小和浏览器窗口的大小是相等的。如果不能全部显示,则滚动浏览器窗口,可以显示出网页的各个部分。

获取视口的大小

网页上的每个元素,都有clientHeight和clientWidth属性。这两个属性指元素的内容部分再加上padding的所占据的视觉面积,不包括border和滚动条占用的空间。

image.png

document元素的clientHeight和clientWidth属性,就代表了视口的大小。

document.documentElement.clientWidth
 document.documentElement.clientHeight

使用的时候,有2个地方需要注意:

  • 这个函数必须在页面加载完成后才能运行,否则document对象还没生成,浏览器会报错。
  • clientWidth和clientHeight都是只读属性,不能对它们赋值。

元素.clientHeight 是元素内容的height+padding
比如:div.clientHeight

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        #test{
            width: 100px;
            height: 150px;
            padding: 20px;
            border: 1px solid red;
        }
    </style>
</head>
<body>
<div id="test">
aaaaaaaaaaaaaaa
    aaaaaaaaaaaaaaa
    aaaaaaaaaaaaaaa
    aaaaaaaaaaaaaaa
    aaaaaaaaaaaaaaa
    aaaaaaaaaaaaaaa
    aaaaaaaaaaaaaaa
    aaaaaaaaaaaaaaa
    aaaaaaaaaaaaaaa
    aaaaaaaaaaaaaaa
</div>

<script>
   console.log(document.documentElement.clientWidth);
   console.log(document.documentElement.clientHeight);
    var div = document.getElementById('test')

   console.log(div.clientWidth);
   console.log(div.clientHeight);
</script>
</body>
</html>

获取网页文档内容大小的方法(不包括溢出的内容)

document.documentElement.offsetWidth

获取DOM文档的根节点html元素对象的宽度,即offsetWidth=width+padding+border,不包括margin。

document.documentElement.offsetHeight

获取DOM文档的根节点html元素对象的高度,有可能小于视口高度(由文档内容高度决定,不包括溢出的内容),即offsetHeight=height+padding+border,不包括margin。

元素.offsetHeight是元素设定的height+padding+border(不包括溢出的内容)
比如:div.offsetHeight

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        *{
            padding: 0;
            margin: 0;
        }
        #test{
            width: 100px;
            height: 150px;
            padding: 20px;
            border: 1px solid red;
        }
    </style>
</head>
<!--可以去掉style="height: 2000px"观察一下-->
<body style="height: 2000px">
<div id="test">
aaaaaaaaaaaaaaaaaaa
    aaaaaaaaaaaaaaaaaaa
    aaaaaaaaaaaaaaaaaaa
    aaaaaaaaaaaaaaaaaaa
    aaaaaaaaaaaaaaaaaaa
    aaaaaaaaaaaaaaaaaaa
    aaaaaaaaaaaaaaaaaaa
    aaaaaaaaaaaaaaaaaaa
    aaaaaaaaaaaaaaaaaaa
    aaaaaaaaaaaaaaaaaaa
    aaaaaaaaaaaaaaaaaaa
    aaaaaaaaaaaaaaaaaaa
    aaaaaaaaaaaaaaaaaaa
    aaaaaaaaaaaaaaaaaaa
</div>

<script>
   console.log(document.documentElement.offsetWidth);
   console.log(document.documentElement.offsetHeight);
    var div = document.getElementById('test')

   console.log(div.offsetWidth);
   console.log(div.offsetHeight);
</script>
</body>
</html>

js实现小球触壁反弹

<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <title></title>
    <style type="text/css">
        #mainBox {
            width: 300px;
            height: 500px;
            background: lavender;
            border: 1px solid gold;
            margin: auto;
            position: relative;
        }

        .ball {
            width: 30px;
            height: 30px;
            background: cyan;
            border-radius: 50%;
            position: absolute;
            left: 0px;
            top: 0px;
        }

    </style>
</head>

<body>
<div id="mainBox">
    <div class="ball">

    </div>
</div>

</body>
<script type="text/javascript">
    //公共变量
    var ball_ = document.getElementsByClassName('ball')[0]
    var mainBox = document.getElementById("mainBox")

    //小球移动变量
    var x = 0;
    var y = 0;
    var speedX = 2;
    var speedY = 2;
    //定时器
    var timer = null;

    timer = setInterval('move()', 10)
    function move() {
        x += speedX;
        y += speedY;
        //判断小球是否碰到边界
        if(x <= 0 || x > mainBox.offsetWidth - ball_.offsetWidth) {
            speedX = -speedX
        }
        if(y <= 0 || mainBox.offsetHeight - ball_.offsetHeight <= y) {
            speedY = -speedY
        }
        //改变小球的left和top值
        ball_.style.left = x + 'px';
        ball_.style.top = y + 'px';

       }
    move();

</script>

</html>

获取网页文档内容大小的方法(包括溢出的内容)

网页上的每个元素还有scrollHeight和scrollWidth属性,指包含滚动条在内的该元素的视觉面积。
那么,document对象的scrollHeight和scrollWidth属性就是网页的大小,意思就是滚动条滚过的所有长度和宽度。

        document.documentElement.scrollWidth
        document.documentElement.scrollHeight

元素.scrollHeight 可以获得元素内容的实际高度,包括溢出的内容。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        *{
            padding: 0;
            margin: 0;
        }
        #test{
            width: 100px;
            height: 150px;
            padding: 20px;
            border: 1px solid red;
        }
    </style>
</head>
<!--可以去掉style="height: 2000px"观察一下-->
<body>
<div id="test">
aaaaaaaaaaaaaaaaaaa
    aaaaaaaaaaaaaaaaaaa
    aaaaaaaaaaaaaaaaaaa
    aaaaaaaaaaaaaaaaaaa
    aaaaaaaaaaaaaaaaaaa
    aaaaaaaaaaaaaaaaaaa
    aaaaaaaaaaaaaaaaaaa
    aaaaaaaaaaaaaaaaaaa
    aaaaaaaaaaaaaaaaaaa
    aaaaaaaaaaaaaaaaaaa
    aaaaaaaaaaaaaaaaaaa
    aaaaaaaaaaaaaaaaaaa
    aaaaaaaaaaaaaaaaaaa
    aaaaaaaaaaaaaaaaaaa
</div>

<script>
   console.log(document.documentElement.scrollWidth);
   console.log(document.documentElement.scrollHeight);
    var div = document.getElementById('test')

   console.log(div.scrollWidth);
   console.log(div.scrollHeight);
</script>
</body>
</html>

获取网页元素的绝对位置

网页元素的绝对位置,指该元素的左上角相对于整张网页左上角的坐标。
这个绝对位置要通过计算才能得到。
首先,每个元素都有offsetTop和offsetLeft属性,表示该元素的左上角与父容器(offsetParent对象)左上角的距离。所以,只需要将这两个值进行累加,就可以得到该元素的绝对坐标。

image.png

下面两个函数可以用来获取绝对位置的横坐标和纵坐标。

function getElementLeft(element){
    var actualLeft = element.offsetLeft;
    var current = element.offsetParent;

    while (current !== null){
      actualLeft += current.offsetLeft;
      current = current.offsetParent;
    }

    return actualLeft;
  }

  function getElementTop(element){
    var actualTop = element.offsetTop;
    var current = element.offsetParent;

    while (current !== null){
      actualTop += current.offsetTop;
      current = current.offsetParent;
    }

    return actualTop;
  }

body的offsetTop是0;body的offsetParent是null

offsetLeft与style.left的区别

offsetLeft 获取的是相对于父对象的左边距

left 获取或设置相对于 具有定位属性(position定义为relative)的父对象 的左边距

如果父div的position定义为relative,子div的position定义为absolute,那么子div的style.left的值是相对于父div的值,
这同offsetLeft是相同的,区别在于:

  1. style.left 返回的是字符串,如28px,offsetLeft返回的是数值28,如果需要对取得的值进行计算,
    还用offsetLeft比较方便。
  2. style.left是读写的,offsetLeft是只读的,所以要改变div的位置,只能修改style.left。
  3. style.left的值需要事先定义,否则取到的值为空。而且必须要定义在html里,我做过试验,如果定义在
    css里,style.left的值仍然 为空,这就是我刚开始碰到的问题,总是取不到style.left的值。

offsetLeft则仍然能够取到,无需事先定义div的位置。

获取网页元素的相对位置

网页元素的相对位置,指该元素左上角相对于浏览器窗口左上角的坐标。
有了绝对位置以后,获得相对位置就很容易了,只要将绝对坐标减去页面的滚动条滚动的距离就可以了。滚动条滚动的垂直距离,是document对象的scrollTop属性;滚动条滚动的水平距离是document对象的scrollLeft属性。

image.png

滚动距离

document.body.scrollTop/scrollLeft
scrollTop是可视区顶部到整个页面顶部的距离(就是滚动条滚动距离);想要得到谁的滚动距离,scrollTop和scrollLeft的前面就写哪个元素

document.documentElement.scrollTop/scrollLeft

兼容性问题

chrome浏览器,认为滚动距离是在body上的

其他浏览器,认为滚动距离是documentElement上的

可以用如下方式解决兼容性问题:

var scrollTop = document.documentElement.scrollTop || document.body.scrollTop

对上一节中的两个函数进行相应的改写,获得元素的相对位置:

function getElementViewLeft(element){
    var actualLeft = element.offsetLeft;
    var current = element.offsetParent;

    while (current !== null){
      actualLeft += current.offsetLeft;
      current = current.offsetParent;
    }

    var scrollLeft = document.documentElement.scrollLeft || document.body.scrollLeft

    return actualLeft-scrollLeft ;
  }

  function getElementViewTop(element){
    var actualTop = element.offsetTop;
    var current = element.offsetParent;

    while (current !== null){
      actualTop += current. offsetTop;
      current = current.offsetParent;
    }

    var scrollTop = document.documentElement.scrollTop || document.body.scrollTop

    return actualTop-scrollTop;
  }

js实现返回顶部功能

<!DOCTYPE html>
<html>

<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>test</title>
    <style>
        body {
            /*height: 5000px;*/
        }
        a {
            position: fixed;
            right: 100px;
            width: 50px;
            height: 50px;
            background: red;
            color: white;
            text-align: center;
            line-height: 50px;
            display: block;
        }
        .toTop {
            bottom: 160px;
        }
        .toBottom {
            bottom: 100px;
        }
    </style>
    <script>
        window.onload = function () {
            var a = document.getElementById('top');
            a.onclick = function () {
                var timeId = setInterval(function () {
                    var scroll_top = document.documentElement.scrollTop || document.body.scrollTop;
                    if(scroll_top == 0)
                    {
                        alert('计时器停止了')
                        clearInterval(timeId);
                    }
                    window.scrollBy(0,-100);

                },50);
            }

            var aBottom = document.getElementById('bottom');

            var viewportHeight = document.documentElement.clientHeight;
            var documentHeight = document.documentElement.scrollHeight;

            aBottom.onclick = function () {
                var timeId = setInterval(function () {
                    var scroll_top = document.documentElement.scrollTop || document.body.scrollTop;
                    if(scroll_top + viewportHeight == documentHeight)
                    {
                        alert('计时器停止了')
                        clearInterval(timeId);
                    }
                    window.scrollBy(0,100);

                },50);
            }
        }
    </script>
</head>

<body style="height: 5000px">
<a href="javascript:;" class="toTop" id ="top">上</a>
<a href="javascript:;" class="toBottom" id="bottom">下</a>
</body>
</html>

下拉加载模拟

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script>
        window.onscroll=function() {
                console.log('正在滑动f');
                var scrollTop = document.documentElement.scrollTop;    //滚动条距离顶部的高度
                var scrollHeight = document.documentElement.scrollHeight;   //当前页面的总高度
                var clientHeight = document.documentElement.clientHeight;    //当前可视的页面高度
                 console.log("top:"+scrollTop+",doc:"+scrollHeight+",client:"+clientHeight);
                if (scrollTop + clientHeight >= scrollHeight) {   //距离顶部+当前高度 >=文档总高度 即代表滑动到底部
                    console.log('下拉');
                    var div = document.createElement('div');
                    div.style.height = 2000+'px';
                    document.getElementById('body').appendChild(div);
                }
            }

    </script>
</head>
<body id="body">
<div style="height: 2000px;" id = "div">

</div>
</body>
</html>

获取元素相对位置的快速方法

除了上面的函数以外,还有一种快速方法,可以立刻获得网页元素的位置。
那就是使用getBoundingClientRect()方法。它返回一个对象,其中包含了left、right、top、bottom四个属性,分别对应了该元素的左上角和右下角相对于浏览器窗口(viewport)左上角的距离。
所以,网页元素的相对位置就是

var X= 元素.getBoundingClientRect().left;

 var Y =元素.getBoundingClientRect().top;

再加上滚动距离,就可以得到绝对位置

 var X=元素.getBoundingClientRect().left+document.documentElement.scrollLeft;

 var Y =元素.getBoundingClientRect().top+document.documentElement.scrollTop;

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        div{
            height: 100px;
            width: 100px;
            background-color: red;
            position: absolute;
            left:200px;
            top: 1000px;
        }
        #btn{
            position: fixed;
            top:20px;
        }
    </style>
    <script>
        window.onload = function () {
            var btn = document.getElementById('btn');

            btn.onclick = function () {
                var scroll_top = document.documentElement.scrollTop || document.body.scrollTop;
                var div = document.getElementById('div')
                var obj = div.getBoundingClientRect();
                console.log("left" + obj.left);//200,div左边距离视口左边的距离
                console.log("top" + obj.top);//300,div顶边距离视口顶边的距离
                console.log("right" + obj.right);//300,div右边距离视口左边的距离
                console.log("bottom" + obj.bottom);//400,div底边距离视口顶边的距离
                console.log("scroll_top" + scroll_top);
                console.log("top绝对" + (obj.top+scroll_top));
            }

        }
    </script>
</head>
<body style="height: 2000px">
<div id="div">

</div>
<input type="button" id="btn" value="ok">
</body>
</html>

谢谢

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,835评论 4 364
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,598评论 1 295
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 109,569评论 0 244
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,159评论 0 213
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,533评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,710评论 1 222
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,923评论 2 313
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,674评论 0 203
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,421评论 1 246
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,622评论 2 245
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,115评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,428评论 2 254
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,114评论 3 238
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,097评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,875评论 0 197
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,753评论 2 276
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,649评论 2 271

推荐阅读更多精彩内容

  • 网页文档的大小和浏览器窗口的大小 首先,要明确两个基本概念。一张网页的全部面积,就是它的大小。通常情况下,网页的大...
    蛋炒饭_By阅读 249评论 0 0
  • 网页文档的大小和浏览器窗口的大小 首先,要明确两个基本概念。一张网页的全部面积,就是它的大小。通常情况下,网页的大...
    数据萌新阅读 371评论 0 0
  • 网页文档的大小和浏览器窗口的大小 首先,要明确两个基本概念。一张网页的全部面积,就是它的大小。通常情况下,网页的大...
    piziyang12138阅读 134评论 0 0
  • 获取视口的大小 网页上的每个元素,都有clientHeight和clientWidth属性。这两个属性指元素的内容...
    金春国_Roy阅读 402评论 0 0
  • 中秋节前一晚,洗完澡,突发奇整理了洗手台。结果毫不费力扔掉了三分之二的东西。为啥毫不费力?因为它们都~过期~了。想...
    戏精请卸妆阅读 82评论 0 0