zoukankan      html  css  js  c++  java
  • DOM-获得元素定位父级及距离

    HTML

    <input type="button" name="" id="" value="点击运动" />
    <div id="div1">
    	<div id="div2">
    		<div id="div3"></div>
    	</div>
    </div>
    

    CSS

    #div1,#div1 div{
    	position: absolute;
    	top: 10px;
    }
    #div1{
    	 100px;
    	height: 100px;
    	background: red;
    	left: 100px;
    	border: 2px solid #000;
    	top: 100px;
    }
    #div2{
    	 60px;
    	height: 60px;
    	background: blue;
    	left: 30px;
    	border: 2px solid #fff;
    }
    #div3{
    	 30px;
    	height: 30px;
    	background: yellow;
    	left: 20px;
    	border: 2px solid orange;
    	transition: 1s left;
    }
    

    JS

    /*
     	DOM节点
     * node.offsetParent最近的有定位属性的祖先节点
     * 		如果祖先节点都没有定位,那么默认为body
     * 
     * node.offsetLeft/node.offsetTop 最近的有定位属性的祖先节点的距离
     * 
     * node.offsetLeft左外边框到定位父级的左内边框的距离
     * node.offsetTop上外边框到定位父级的上内边框的距离
     * 
     * 
     * node.getBoundingClientRect()
     * node.getBoundingClientRect().left
     * 	获取元素的盒模型信息
     * 	返回值为一个对象
     * 		left top bottom right width height 
     * 		相对于浏览器可视区域
     * 		注意:获取的值会根据滚动条滚动的距离变换的
     * 		
     * 
     *
     * 
     * */
    
    //点击按钮,div3运动到窗口边上
    var oBtn=document.getElementsByTagName("input")[0];
    var oDiv3=document.getElementById("div3");
    oBtn.onclick=function(){
    	oDiv3.style.left=-(oDiv3.getBoundingClientRect().left-parseInt(oDiv3.offsetLeft))+"px";
    }
    

      

  • 相关阅读:
    50个SQL语句(MySQL版) 问题六
    50个SQL语句(MySQL版) 问题五
    50个SQL语句(MySQL版) 问题四
    50个SQL语句(MySQL版) 问题三
    50个SQL语句(MySQL版) 问题二
    50个SQL语句(MySQL版) 问题一
    50个SQL语句(MySQL版) 建表 插入数据
    相邻元素margin的自动合并与float的坑
    STL之list
    你真的会用搜索吗?—— google 搜索技巧
  • 原文地址:https://www.cnblogs.com/yangxue72/p/8006562.html
Copyright © 2011-2022 走看看