offset 和 client
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <style> .testDOM { width: 200px; height: 200px; background-color: #2de; padding: 20px; border: 10px solid #ec6; margin: 20px; } </style> </head> <body> <div class="testDOM"></div> <script> let test = document.querySelector('.testDOM') console.log('offsetWidth', test.offsetWidth) // width + padding(左右) + border(左右)260 console.log('offsetHeight', test.offsetHeight) // height + padding(上下) + border(上下)260 // 获取元素的坐标,相对于其最近的定位的上级元素的坐标。否则,相对于body。 console.log('offsetLeft', test.offsetLeft) // 28 body有8px的padding console.log('offsetTop', test.offsetTop) // 20 // 获取元素的最近的定位的上级元素 没有最近的定位的上级元素,所以获取body console.log('offsetParent', test.offsetParent) // <body> console.log('clientWidth', test.clientWidth) // width + padding(左右) 240 console.log('clientHeight', test.clientHeight) // height + padding(上下) 240 // 获取元素的坐标,获取当前节点对象的padding的外边界,距离border外边界的距离。实际上就是左边框的厚度。 console.log('offsetLeft', test.offsetLeft) // 28 console.log('offsetTop', test.offsetTop) // 20 // 获取当前节点对象的宽度和高度,返回数字,不包含单位。 console.log('scrollWidth', test.scrollWidth) // width+padding(左右)+ 溢出部分 240 console.log('scrollHeight', test.scrollHeight) // height+padding(上下)+ 溢出部分 240 </script> </body> </html>

scroll
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <style> * { margin: 0; padding: 0; } .father { width: 300px; height: 300px; background-color: #3de; margin: 100px auto; padding: 10px; overflow: auto; border: 10px solid red; } .son { width: 400px; height: 600px; background-color: yellowgreen; } </style> </head> <body> <div class="father"> <div class="son"></div> </div> <script> var fNode = document.querySelector('.father') fNode.onscroll = function () { // 获取元素中被卷去的内容的距离 获取元素内部总被卷去的内容的横向距离 和 纵向距离 console.log('x:' + fNode.scrollLeft) console.log('y:' + fNode.scrollTop) } </script> </body> </html>
