一、offset(偏移)
JS:
// 父元素中存在position時,獲取該元素相對第一個具有定位的父元素的距離
// 父元素中不存在position時,獲取元素相對祖先元素html的距離
// 獲取的距離會自動取整(測試時谷歌三舍四入、火狐四舍五入)
let offsetLeft = document.getElementById('s_box').offsetLeft let offsetTop = document.getElementById('s_box').offsetTop // 獲取元素的大小(border內,含border、含滾動條)
let offsetWidth = document.getElementById('s_box').offsetWidth let offsetHeight = document.getElementById('s_box').offsetHeight // 獲取body寬高
let bodyWidth = document.querySelector('body').offsetWidth let bodyHeight = document.querySelector('body').offsetHeight
JQ:
// 始終獲取的元素距離body的距離,保留小數
$('#s_box').offset().top $('#s_box').offset().left
二、client(當前)
// 獲取元素border寬度
let clientLeft = document.getElementById('s_box').clientLeft let clientTop = document.getElementById('s_box').clientTop // 獲取元素可視范圍的寬高(border內,不含border、不含滾動條)
let clientWidth = document.getElementById('s_box').clientWidth let clientHeight = document.getElementById('s_box').clientHeight // 獲取可視區的高度
document.documentElement.clientHeight
三、scroll(滾動)
// 獲取頁面滾動距離
// 沒有DOCTYPE聲明==>23467有效
// 有DOCTYPE聲明==>12345有效
console.log(document.documentElement.scrollTop, '---->1') console.log(window.pageYOffset, '---->2') console.log($(window).scrollTop(), '---->3') console.log($(document).scrollTop(), '---->4') console.log($('html').scrollTop(), '---->5') console.log(document.body.scrollTop, '---->6') console.log($('html body').scrollTop(), '---->7') // js兼容寫法
let bodyScrollTop = document.documentElement.scrollTop || document.body.scrollTop || window.pageYOffset; // 獲取子元素在父元素內的滾動距離,即父容器滾動距離(這里的#box是父元素)
$('#box').scroll(function () { console.log($('#box').scrollTop()) console.log(document.getElementById('box').scrollTop) }) //滾動位置可以重寫,其他xxTop、xxLeft都是只讀
$('#box').scrollTop(100) //scrollHeight,個人理解是指元素滾動范圍的高度
//scrollHeight=父容器高度(不含border)+元素可滾動的最大距離(即scrollTop最大值)
//scrollHeight=子元素高度(含border)+父容器的padding
console.log(document.getElementById('box').scrollHeight)
四、X、Y
$('#box').click(function(e){ // 鼠標點擊位置相對父容器的坐標
console.log(e.offsetX) console.log(e.offsetY) // 鼠標點擊位置相對文檔視口的坐標(不受滾動條影響)
console.log(e.clientX) console.log(e.clientY) // 鼠標點擊位置屏幕的坐標
console.log(e.screenX) console.log(e.screenY) // 鼠標點擊位置相對整個文檔的坐標(隨滾動條變化)
console.log(e.pageX) console.log(e.pageY) })
實用demo:通過外部點擊操作,使盒子內對應元素滾動到盒子頂部
$('.content_select').on('click', '.content_select_circular', function (e) { let num = $(this).index() let scrollTop = $('#box').scrollTop();//父容器滾動距離
let dotop = $('#box>.subject').eq(num).offset().top;//滾動元素距離文檔頂部距離
let hei = $('#box').offset().top;//父容器距離文檔頂部距離
$('#box').animate({ scrollTop: scrollTop + dotop - hei }, 500); })