企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
[TOC] ## 1. offset ``` offsetParent //获取给了定位元素的父级 offsetLeft //返回元素的相对定位父元素水平偏移位置。 返回number offsetTop //返回元素的相对定位父元素水平垂直偏移位置。 offsetWidth //返回元素的宽度 -- 包含width,padding,border offsetHeight //返回元素的高度 ``` ``` <script> var child = document.getElementById("child"); var parent = child.offsetParent; var left = child.offsetLeft; var offsetTop = child.offsetTop; var offsetWidth = child.offsetWidth; console.log(parent) console.log(left); console.log(offsetTop); console.log(offsetWidth) </script> ***** //获取顶部的高度 // $(element).offset().top /* $(function(){ var top = $("#child").offset().top; console.log(top); }) */ /* $(()=>{ var top = $("#child").offset().top; console.log(top); }) */ window.onload = function() { function getTop(element){ var realTop = element.offsetTop; var parent = element.offsetParent; while (parent !== null){ realTop += parent.offsetTop; parent = parent.offsetParent; } return realTop; } var child = document.getElementById("child"); var top = getTop(child); console.log(top); } ``` ### 1.1 用法 获取宽度或高度 > 用offsetWidth获取子元素的宽度, ``` <style> #parent>div{ width: 200px; height: 100px; border: 1px solid #333; float: left; } #parent{ margin-left: auto; margin-right: auto; overflow: hidden; } </style> ***** <div id="parent"> <div id="child"></div> <div></div> <div></div> <div></div> </div> <script> // offsetWidth var parent = document.getElementById("parent"); var childWidth = document.getElementById("child").offsetWidth; parent.style.width = childWidth*4 + "px"; </script> ``` ## 2.可视区域 > scrollWodth scrollHeight > 布局视口的宽度 var ww = window.innerWidth; > 设备视口的宽度 var dw = document.documentElement.clientWidth; ``` <script> //可视区域的width var ww = window.innerWidth; var dw = document.documentElement.clientWidth; console.log(ww); console.log(dw); </script> ``` ## 3. getPropertyValue/removeProperty ``` <p id="test" style="border: 1px solid #333;color: red;">hello world</p> <script> window.onload = function(){ // debugger; var test = document.getElementById("test"); test.onclick = function(){ // var length = this.style.length; // var color = this.style.getPropertyValue("color") // alert(this.style.item(0)); console.log(this.style); // this.style.removeProperty("color"); this.style.setProperty("color","yellow"); console.log(color); } } </script> ```