Obtaining Browser Scrollbar Dimensions in JavaScript
Determining the dimensions of scrollbars in a browser is essential for creating dynamic web pages. This article explores a method to determine the height of horizontal scrollbars and the width of vertical ones using JavaScript.
Solution:
The code snippet provided below calculates the width of a vertical scrollbar using a clever technique.
function getScrollBarWidth() { // Create elements to measure scrollbar size var inner = document.createElement('p'); inner.style.width = "100%"; inner.style.height = "200px"; var outer = document.createElement('div'); outer.style.position = "absolute"; outer.style.top = "0px"; outer.style.left = "0px"; outer.style.visibility = "hidden"; outer.style.width = "200px"; outer.style.height = "150px"; outer.style.overflow = "hidden"; outer.appendChild(inner); // Add elements to the DOM document.body.appendChild(outer); // Calculate scrollbar width var w1 = inner.offsetWidth; outer.style.overflow = 'scroll'; var w2 = inner.offsetWidth; if (w1 == w2) w2 = outer.clientWidth; // Remove elements from the DOM document.body.removeChild(outer); // Return scrollbar width return (w1 - w2); }
Explanation:
This function creates two elements, an inner element (inner) and an outer element (outer). The inner element has a fixed size while the outer element does not have its overflow property set. The width difference between these elements after enabling overflow on the outer element represents the width of the vertical scrollbar.
The above is the detailed content of How Can I Get the Dimensions of Browser Scrollbars Using JavaScript?. For more information, please follow other related articles on the PHP Chinese website!