Two examples of JavaScript computing the width of a scroll bar

Source: Internet
Author: User


Describes the placeholder for the bottom scroll bar before calculating the scroll bar. In a PC browser, the scroll bar is the inner margin and content area of the placeholder element, while in mobile browsers, the scroll bar is not occupying the inner margin and content area, and is also hidden in time. Therefore, you only need to calculate the width of the scroll bar in your PC browser, especially if the full screen window is not scrollable.

Detailed methods are as follows (Offsetwidth-clientwidth):

function Getscrollbarwidth () {
var OP = document.createelement (' P '),
Styles = {
Width: ' 100px ',
Height: ' 100px ',
Overflowy: ' Scroll '
}, I, scrollbarwidth;
For (i in styles) op.style[i] = styles[i];
Document.body.appendChild (OP);
Scrollbarwidth = Op.offsetwidth-op.clientwidth;
Op.remove ();
return scrollbarwidth;
}
About offsetwidth and clientwidth more knowledge to refer to JS learning 13:screen/client/offset/scroll/inner/avail width/left.

Method 2 (Clientwidth-clientwidth):

Function Getscrollbarwidth () {
 var OP = document.createelement (' P '),
  styles = {
 & Nbsp; width: ' 100px ',
   height: ' 100px '
  }, I, ClientWidth1, ClientWidth2, Scrollbarwidth;
 for (i in styles) op.style[i] = styles[i];
 document.body.appendchild (OP);
 clientwidth1 = op.clientwidth;
 op.style.overflowy = ' scroll ';
 clientwidth2 = op.clientwidth;
 scrollbarwidth = clientwidth1-clientwidth2;
 op.remove ();
 return scrollbarwidth;
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.