Hide scrollbar with overflow:scroll enabled

前端 未结 4 552
没有蜡笔的小新
没有蜡笔的小新 2020-12-30 08:41

I need to hide the scrollbar on a div that has overflow:scroll; enabled so that the div will scroll with mouse and keyboard but the scrollbar itself will not be displayed.

4条回答
  •  萌比男神i
    2020-12-30 09:18

    @Maloric answer pointed me in the correct direction, however I needed fluid width, and I also wanted to be more accurate on the width of the scrollbar.

    Here is a function that will return the exact width of the scrollbar based on what the browser reports.

    var getWidth = function () {
        var scrollDiv = document.createElement('div'),
            scrollbarWidth;
    
        scrollDiv.style.overflow = 'scroll';
        document.body.appendChild(scrollDiv);
    
        scrollbarWidth = scrollDiv.offsetWidth - scrollDiv.clientWidth;
        
        document.body.removeChild(scrollDiv);
    
        return scrollbarWidth;
    };
    
    var width = getWidth();
    var container = document.querySelector('.overflowing-container');
    
    container.style.paddingRight = width + 'px';
    container.style.marginRight = (width * -1) + 'px';
    
    // Just for testing purposes
    document.querySelector('.scrollbar-width').innerHTML = 'scrollbar height: ' + getWidth()
    .container {
      height: 200px;
      overflow-x: hidden;
      overflow-y: auto;
      width: 500px;
    }
    
    .overflowing-container {
      height: 100%;
      overflow-y: auto;
      width: 100%;
    
    }
    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris tristique feugiat metus, eget mollis nibh vestibulum eu. Nullam eros orci, gravida eu quam nec, maximus posuere dui. Maecenas erat magna, elementum eget nunc eget, tincidunt varius nisl. Phasellus pretium congue consectetur. Donec rutrum nisi sed eros posuere, vel pretium nunc viverra. Praesent consequat sagittis urna, quis convallis magna gravida et. In sed eleifend arcu. Duis ornare condimentum est luctus malesuada. Morbi nec sodales nunc. Morbi vehicula tristique massa, nec lacinia tellus vulputate fringilla. Nam eget pulvinar libero. Vestibulum ligula mi, tincidunt ac pellentesque vitae, convallis eu tortor. Cras varius dolor sit amet libero rhoncus, mattis aliquet augue porttitor. Etiam sollicitudin, sem ut mollis imperdiet, erat enim gravida tortor, et imperdiet sem nibh in ex. Aliquam ac aliquam risus. Suspendisse gravida suscipit sapien, et ultrices massa ornare eget. Nulla venenatis pellentesque arcu at auctor. Sed libero ligula, pretium in metus a, malesuada ullamcorper leo. Vivamus tempor velit in ante fringilla rhoncus. Nam ac iaculis arcu. Mauris a nisi quis arcu feugiat posuere.

    The above snippet shows this in action.

提交回复
热议问题