programing

JavaScript를 사용하여 스크롤 막대 너비 가져 오기

nasanasas 2020. 8. 17. 09:08
반응형

JavaScript를 사용하여 스크롤 막대 너비 가져 오기


이 질문에 이미 답변이 있습니다.

다음 HTML은 div.container의 오른쪽 안쪽 가장자리에 스크롤 막대를 표시합니다.

스크롤 막대의 너비를 결정할 수 있습니까?

<div class="container" style="overflow-y:auto; height:40px;">
  <div class="somethingBig"></div>
</div>

이 함수는 스크롤바의 너비를 제공해야합니다.

function getScrollbarWidth() {

  // Creating invisible container
  const outer = document.createElement('div');
  outer.style.visibility = 'hidden';
  outer.style.overflow = 'scroll'; // forcing scrollbar to appear
  outer.style.msOverflowStyle = 'scrollbar'; // needed for WinJS apps
  document.body.appendChild(outer);

  // Creating inner element and placing it in the container
  const inner = document.createElement('div');
  outer.appendChild(inner);

  // Calculating difference between container's full width and the child width
  const scrollbarWidth = (outer.offsetWidth - inner.offsetWidth);

  // Removing temporary elements from the DOM
  outer.parentNode.removeChild(outer);

  return scrollbarWidth;

}

기본 단계는 다음과 같습니다.

  1. 숨겨진 div (외부)를 만들고 오프셋 너비를 가져옵니다.
  2. CSS 오버플로 속성을 사용하여 div (외부)에 강제로 스크롤 막대 표시
  3. 새 div (내부)를 만들고 바깥쪽에 추가하고 너비를 '100 %'로 설정하고 오프셋 너비를 가져옵니다.
  4. 수집 된 오프셋을 기반으로 스크롤바 너비 계산

작업 예 : http://jsfiddle.net/slavafomin/tsrmgcu9/

최신 정보

Windows (메트로) 앱에서 이것을 사용하는 경우 ' outer'div-ms-overflow-style 속성 을로 설정해야합니다 scrollbar. 그렇지 않으면 너비가 올바르게 감지되지 않습니다. (코드 업데이트 됨)

업데이트 # 2 기본 "스크롤 할 때 스크롤바 만 표시"설정 (Yosemite 이상)을 사용하는 Mac OS에서는 작동하지 않습니다.


// offsetWidth 에는 스크롤 막대의 너비가 포함되고 clientWidth 에는 포함 되지 않습니다. 일반적으로 14-18px입니다. 그래서:

 var scrollBarWidth = element.offsetWidth - element.clientWidth;

자식이 스크롤바 (기본값)를 제외한 컨테이너의 전체 너비를 사용하는 경우 너비를 뺄 수 있습니다.

var child = document.querySelector(".somethingBig");
var scrollbarWidth = child.parentNode.offsetWidth - child.offsetWidth;

간단하고 빠르다고 생각합니다.

var scrollWidth= window.innerWidth-$(document).width()

컨테이너가 한 번만 페이지에 있고 jQuery를 사용한다고 가정하면 다음과 같습니다.

var containerEl = $('.container')[0];
var scrollbarWidth = containerEl.offsetWidth - containerEl.clientWidth;

자세한 내용 이 답변 을 참조하십시오.


I've used next function to get scrollbar height/width:

function getBrowserScrollSize(){

    var css = {
        "border":  "none",
        "height":  "200px",
        "margin":  "0",
        "padding": "0",
        "width":   "200px"
    };

    var inner = $("<div>").css($.extend({}, css));
    var outer = $("<div>").css($.extend({
        "left":       "-1000px",
        "overflow":   "scroll",
        "position":   "absolute",
        "top":        "-1000px"
    }, css)).append(inner).appendTo("body")
    .scrollLeft(1000)
    .scrollTop(1000);

    var scrollSize = {
        "height": (outer.offset().top - inner.offset().top) || 0,
        "width": (outer.offset().left - inner.offset().left) || 0
    };

    outer.remove();
    return scrollSize;
}

This jQuery-based solutions works in IE7+ and all other modern browsers (including mobile devices where scrollbar height/width will be 0).


If you use jquery.ui, try this code:

$.position.scrollbarWidth()

Here's an easy way using jQuery.

var scrollbarWidth = jQuery('div.withScrollBar').get(0).scrollWidth - jQuery('div.withScrollBar').width();

Basically we subtract the scrollable width from the overall width and that should provide the scrollbar's width. Of course, you'd want to cache the jQuery('div.withScrollBar') selection so you're not doing that part twice.


this worked for me..

 function getScrollbarWidth() { 
    var div = $('<div style="width:50px;height:50px;overflow:hidden;position:absolute;top:-200px;left:-200px;"><div style="height:100px;"></div>'); 
    $('body').append(div); 
    var w1 = $('div', div).innerWidth(); 
    div.css('overflow-y', 'scroll'); 
    var w2 = $('div', div).innerWidth(); 
    $(div).remove(); 
    return (w1 - w2); 
}

참고URL : https://stackoverflow.com/questions/13382516/getting-scroll-bar-width-using-javascript

반응형