zoukankan      html  css  js  c++  java
  • 我的前端工具集(八)获得html元素在页面中的位置

    我的前端工具集(八)获得html元素在页面中的位置

     

    liuyuhang原创,未经允许禁止转载

    目录

    我的前端工具集

    有时候需要用点击等操作,来获取某元素在页面中的位置,然后在该位置添加某些操作

    如进度条,提示框,特效动画等。(bootstrap提示工具也挺好用的)。

    1.html代码

        <div style="padding:10px">
            <h2>This is a page to test Postion.</h2>
            <div id="token" style="padding:5px"></div>
            <br>
            <div class="col-lg-3" style="margin-top:20px">
                <button type="button" run="button001" class="btn btn-default" onclick="test(this)">测试</button>
            </div>
        </div>

     当然也可以用监听器的方式来获取当前监听对象,如果是用onclick,可使用this方式来获取当前对象。

     如果是操作其他元素获取绝对位置,自行写吧还是!

    2.js代码

        function test(me){
            var top = $(me).offset().top;//获取该元素相对于浏览器的位置top
            var left = $(me).offset().left;//获取该元素相对于浏览器的位置left
            //var top = $(me).position().top;//获取该元素相对于父元素的位置top
            //var left = $(me).position().left;//获取该元素相对于父元素的位置left
            console.log(top)
            console.log(left)
            //写点内容到刚刚获取到的位置,position:fixed是相对于浏览器定位
            $("body").append("<div style=';position:fixed;top:" + top + ";left:" + left + "'><h3>got it</h3></div>")
        }

    3.测试结果

      页面和console

      点击测试按钮后

    以上!

  • 相关阅读:
    linux格式化新硬盘并挂载,设置开机自动挂载
    各大名企的笔试面试题
    web2.0 Color
    选调生面试题
    网站流量概要分析
    css下拉菜单演示
    子查询
    技巧
    CMM与软件生命周期
    学习方法之PHP
  • 原文地址:https://www.cnblogs.com/liuyuhangCastle/p/9846984.html
Copyright © 2011-2022 走看看