使用CSS定位水平滚动条

问题描述 投票:0回答:1

MacOS 为触控板用户隐藏滚动条,这导致我的用户不知道他们可以水平滚动结果集。我正在尝试使用 CSS 仅定位水平滚动条,以便我可以使它们永久可见。

我可以使用 CSS 覆盖滚动条的视觉行为:

::-webkit-scrollbar{
    -webkit-appearance: none;
    width: 7px;
}
::-webkit-scrollbar-thumb{
    border-radius: 4px;
    background-color: rgba(0,0,0,.5);
    box-shadow: 0 0 1px rgba(255,255,255,.5);
}

https://jsfiddle.net/ypk62h8v/1/

但是当我尝试应用 :horizontal 伪元素时,它不起作用(Mac/Chrome):

HTML:

<div class="frame" style="">
    <div style="width:500px;height:500px;">
    SCROLLABLE
    </div>
</div>

CSS:

.frame {
    overflow-y: auto;
    overflow-x: auto;
    border: 1px solid black;
    height: 3em;
    width: 10em;
    line-height: 1em;
}

::-webkit-scrollbar:horizontal {
    -webkit-appearance: none;
    width: 7px;
}
::-webkit-scrollbar-thumb:horizontal {
    border-radius: 4px;
    background-color: rgba(0,0,0,.5);
    box-shadow: 0 0 1px rgba(255,255,255,.5);
}

https://jsfiddle.net/ypk62h8v/

css scrollbar
1个回答
0
投票

没有像 :horizontal 这样的直接 CSS 选择器,您可以使用它来专门定位水平滚动条进行自定义,就像您可以在不指定方向的情况下定位滚动条一样。

所以,如果你想实现这一点,你应该使用以下 CSS 和 JavaScript 代码:

// Add a class to the frame when the content overflows horizontally
const frame = document.querySelector('.frame');
const content = document.querySelector('.content');

frame.addEventListener('scroll', () => {
    if (content.scrollWidth > frame.offsetWidth) {
        frame.classList.add('has-horizontal-scroll');
    } else {
        frame.classList.remove('has-horizontal-scroll');
    }
});
.frame {
    overflow-y: auto;
    overflow-x: auto;
    border: 1px solid black;
    height: 3em;
    width: 10em;
    line-height: 1em;
}

.frame::-webkit-scrollbar {
    width: 7px;
    height: 7px;
}

.frame::-webkit-scrollbar-thumb {
    border-radius: 4px;
    background-color: rgba(0, 0, 0, .5);
    box-shadow: 0 0 1px rgba(255, 255, 255, .5);
}

.frame::-webkit-scrollbar-thumb:vertical {
    background-color: rgba(0, 0, 0, .5); /* Adjust vertical scrollbar appearance */
}


.frame.has-horizontal-scroll::-webkit-scrollbar-thumb:horizontal {
    background-color: rgba(0, 0, 0, .5); /* Adjust horizontal scrollbar appearance */
}
<div class="frame" style="">
    <div class="content" style="width:500px;height:500px;">
        SCROLLABLE
    </div>
</div>

© www.soinside.com 2019 - 2024. All rights reserved.