想到解释什么是offsetHeight, clientHeight和scrollHeight或offsetWidth, clientWidth和scrollWidth之间的区别?
在客户端工作之前,必须了解这个区别。否则他们的一半生命将花在修复UI上。
小提琴,或内联如下:
function whatis(propType) { var mainDiv = document.getElementById("MainDIV"); if (window.sampleDiv == null) { var div = document.createElement("div"); window.sampleDiv = div; } div = window.sampleDiv; var propTypeWidth = propType.toLowerCase() + "Width"; var propTypeHeight = propType + "Height"; var computedStyle = window.getComputedStyle(mainDiv, null); var borderLeftWidth = computedStyle.getPropertyValue("border-left-width"); var borderTopWidth = computedStyle.getPropertyValue("border-top-width"); div.style.position = "absolute"; div.style.left = mainDiv.offsetLeft + Math.round(parseFloat((propType == "client") ? borderLeftWidth : 0)) + "px"; div.style.top = mainDiv.offsetTop + Math.round(parseFloat((propType == "client") ? borderTopWidth : 0)) + "px"; div.style.height = mainDiv[propTypeHeight] + "px"; div.style.lineHeight = mainDiv[propTypeHeight] + "px"; div.style.width = mainDiv[propTypeWidth] + "px"; div.style.textAlign = "center"; div.innerHTML = propTypeWidth + " X " + propTypeHeight + "( " + mainDiv[propTypeWidth] + " x " + mainDiv[propTypeHeight] + " )"; div.style.background = "rgba(0,0,255,0.5)"; document.body.appendChild(div); } document.getElementById("offset").onclick = function() { whatis('offset'); } document.getElementById("client").onclick = function() { whatis('client'); } document.getElementById("scroll").onclick = function() { whatis('scroll'); } #MainDIV { border: 5px solid red; } <button id="offset">offsetHeight & offsetWidth</button> <button id="client">clientHeight & clientWidth</button> <button id="scroll">scrollHeight & scrollWidth</button> <div id="MainDIV" style="margin:auto; height:200px; width:400px; overflow:auto;"> <div style="height:400px; width:500px; overflow:hidden;"> </div> </div>