Удивительно, но там нет отличного, простого решения, использующего ванильный JavaScript. Я сделал чистое JS легкое, минимальное кросс-браузерное решение. Настройка ваших собственных потребностей и эстетики
Обновление включает перемещаемой пролистайте:
Вот является fiddle и CodePen
HTML
<body>
<div id="main" class="scrollable">
<div class="content-wrapper">
<div class="content">
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Incidunt accusamus maxime voluptatem quasi. Recusandae optio nobis ratione iste consectetur consequatur cupiditate saepe laborum natus neque a provident eum explicabo delectus qui accusantium nostrum reiciendis soluta hic ut at sed laboriosam possimus repudiandae deserunt velit rerum. Aliquam ratione itaque corrupti aperiam quisquam unde aspernatur odio id repellendus corporis eaque expedita in ab minus possimus! Quo tempore consequatur repellat consectetur nemo molestiae perferendis ipsum esse nesciunt blanditiis nobis dicta? Laudantium quaerat inventore deleniti exercitationem explicabo quos pariatur sunt earum labore sed eius blanditiis architecto consequuntur ad consectetur unde sapiente nisi. Sunt eos.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Incidunt accusamus maxime voluptatem quasi. Recusandae optio nobis ratione iste consectetur consequatur cupiditate saepe laborum natus neque a provident eum explicabo delectus qui accusantium nostrum reiciendis soluta hic ut at sed laboriosam possimus repudiandae deserunt velit rerum. Aliquam ratione itaque corrupti aperiam quisquam unde aspernatur odio id repellendus corporis eaque expedita in ab minus possimus! Quo tempore consequatur repellat consectetur nemo molestiae perferendis ipsum esse nesciunt blanditiis nobis dicta? Laudantium quaerat inventore deleniti exercitationem explicabo quos pariatur sunt earum labore sed eius blanditiis architecto consequuntur ad consectetur unde sapiente nisi. Sunt eos.</p>
</div>
</div>
</div>
<div>Not special and not contained within scrolling</div>
</body>
CSS
.scrollable {
padding: 0% 10%;
position: relative;
border: 1px solid gray;
overflow: hidden;
height: 400px;
}
.scrollable.showScroll::after {
position: absolute;
content: '';
top: 5%;
right: 7px;
height: 90%;
width: 3px;
background: rgba(224, 224, 255, .3);
}
.scrollable .content-wrapper {
width: 100%;
height: 100%;
padding-right: 50%;
overflow-y: scroll;
}
.scroller {
z-index: 5;
cursor: pointer;
position: absolute;
width: 10px;
border-radius: 5px;
background: rgb(111, 111, 190);
top: 0px;
right: 3px;
-webkit-transition: top .08s;
-moz-transition: top .08s;
-ms-transition: top .08s;
-o-transition: top .08s;
transition: top .08s;
}
.content {
-webkit-touch-callout: none;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
JS
(function() {
var scrollContainer = document.querySelector('.scrollable'),
scrollContentWrapper = document.querySelector('.scrollable .content-wrapper'),
scrollContent = document.querySelector('.scrollable .content'),
contentPosition = 0,
scrollerBeingDragged = false,
scroller,
topPosition,
scrollerHeight;
function calculateScrollerHeight() {
// *Calculation of how tall scroller should be
var visibleRatio = scrollContainer.offsetHeight/scrollContentWrapper.scrollHeight;
return visibleRatio * scrollContainer.offsetHeight;
}
function moveScroller(evt) {
// Move Scroll bar to top offset
var scrollPercentage = evt.target.scrollTop/scrollContentWrapper.scrollHeight;
topPosition = scrollPercentage * (scrollContainer.offsetHeight - 5); // 5px arbitrary offset so scroll bar doesn't move too far beyond content wrapper bounding box
scroller.style.top = topPosition + 'px';
}
function startDrag(evt) {
normalizedPosition = evt.pageY;
contentPosition = scrollContentWrapper.scrollTop;
scrollerBeingDragged = true;
}
function stopDrag(evt) {
scrollerBeingDragged = false;
}
function scrollBarScroll(evt) {
if (scrollerBeingDragged === true) {
var mouseDifferential = evt.pageY - normalizedPosition;
var scrollEquivalent = mouseDifferential * (scrollContentWrapper.scrollHeight/scrollContainer.offsetHeight);
scrollContentWrapper.scrollTop = contentPosition + scrollEquivalent;
}
}
function createScroller() {
// *Creates scroller element and appends to '.scrollable' div
// create scroller element
scroller = document.createElement("div");
scroller.className = 'scroller';
// determine how big scroller should be based on content
scrollerHeight = calculateScrollerHeight();
if (scrollerHeight/scrollContainer.offsetHeight < 1){
// *If there is a need to have scroll bar based on content size
scroller.style.height = scrollerHeight + 'px';
// append scroller to scrollContainer div
scrollContainer.appendChild(scroller);
// show scroll path divot
scrollContainer.className += ' showScroll';
// attach related draggable listeners
scroller.addEventListener('mousedown', startDrag);
window.addEventListener('mouseup', stopDrag);
window.addEventListener('mousemove', scrollBarScroll)
}
}
createScroller();
// *** Listeners ***
scrollContentWrapper.addEventListener('scroll', moveScroller);
}());
Концепция проста. У нас есть главный div с «прокручиваемым» классом. JavaScript распознает этот элемент и добавляет скроллер-дивер, который можно стилизовать самостоятельно с помощью CSS. Вложенным дочерним div-оболочкой content-wrapper мы можем эффективно нажимать собственный скроллер вне родительского div, все еще контролируя отступы.
Вот схема:
Причина, почему мы должны поддерживать нативную возможность прокрутки происходит потому, что событие прокрутки JavaScript срабатывает только на элементах, которые перелив набор для прокрутки.См. MDN reference on scroll. Преимущество состоит в том, что если JS отключен, мы все равно грациозно отменим прокрутку без полосы прокрутки.
ПРИМЕЧАНИЕ
Следует отметить, что вам придется настроить свою версию, чтобы пересчитать размер скроллер в некоторых случаях:
1.) Где изменяет размер экрана или
2.) Если более содержимое добавляется.
Во-вторых, изменения должны быть сделаны, если у вас есть несколько «прокручиваемых» элементов. В этом случае вам нужно будет перебрать эти элементы, чтобы как добавить div скроллера, так и прослушать событие прокрутки.
Некоторые браузеры позволяют вам настраивать собственную полосу прокрутки. Я не рекомендую использовать пользовательскую полосу прокрутки, потому что если что-то сломается в вашем JS-коде, пользователи не смогут прокручивать. – Oriol
Будет ли ['noraesae/perfect-scrollbar'] (https://github.com/noraesae/perfect-scrollbar) работать на вас? [** DEMO **] (http://noraesae.github.io/perfect-scrollbar/). В нем указано, что «* perfect-scrollbar является минималистичным, но идеальным (для меня и, возможно, для большинства разработчиков) плагином прокрутки, работающим с jQuery или ** ванильным JavaScript ** **.* " – h2ooooooo
Вы можете сделать свою собственную полосу прокрутки с помощью js, используя события, и вручную установить положение элементов и прокрутку содержимого, это было бы не так сложно, но я думаю, должно быть какое-то лучшее решение. – Mykybo