【前端】js 动态修改滚动条样式
//js 动态修改滚动条样式 参数 滚动条颜色
function scroll(color) {
let scrollStyle = `
<style css-id="scroll">
/* 滚动条 */
/*定义整个滚动条高宽及背景:高宽分别对应横竖滚动条的尺寸 滚动条宽度 滚动条轨道背景颜色*/
::-webkit-scrollbar
{
width:20px;
background-color:#F5F5F5;
}
/*定义滚动条轨道:内阴影+圆角 + 轨道背景颜色*/
::-webkit-scrollbar-track
{
background-color:#f5f5f5;
}
/*定义滑块:内阴影+圆角 样式 */
::-webkit-scrollbar-thumb
{
border-radius:10px;
background-color:${color};
box-shadow:inset 0 0 6px #fff;
}
</style>
`
let div = document.createElement("div");
let _scrollNode = document.querySelector("[css-id='scroll']") || null;
if (_scrollNode) {
document.querySelector("head").removeChild(document.querySelector("[css-id='scroll']"));
}
div.innerHTML = scrollStyle;
let newScrollNode = div.querySelector("[css-id='scroll']");
document.getElementsByTagName("head")[0].appendChild(newScrollNode)
}
//使用
scroll('#e5e7eb')
横轴的滚动条
::-webkit-scrollbar
//js 动态修改滚动条样式 透明背景 参数 滚动条颜色
function scroll(color) {
let scrollStyle = `
<style css-id="scroll">
/* 滚动条 */
/*定义整个滚动条高宽及背景:高宽分别对应横竖滚动条的尺寸 滚动条宽度 滚动条轨道背景颜色*/
::-webkit-scrollbar
{
width:20px;
background-color:#F5F5F54a;
}
/*定义滚动条轨道:内阴影+圆角 + 轨道背景颜色*/
::-webkit-scrollbar-track
{
/* background-color:#f5f5f5;*/
}
/*定义滑块:内阴影+圆角*/
::-webkit-scrollbar-thumb
{
border-radius:10px;
background-color:${color};
}
</style>
`
let div = document.createElement("div");
let _scrollNode = document.querySelector("[css-id='scroll']") || null;
if (_scrollNode) {
document.querySelector("head").removeChild(document.querySelector("[css-id='scroll']"));
}
div.innerHTML = scrollStyle;
let newScrollNode = div.querySelector("[css-id='scroll']");
document.getElementsByTagName("head")[0].appendChild(newScrollNode)
}
//使用
scroll('#ffffff')
/*定义滑块:内阴影+圆角 样式 */
::-webkit-scrollbar-thumb
{
border-radius:10px;
background-color:${color};
box-shadow:inset 0 0 6px #fff;
}
::-webkit-scrollbar {
width: 6px;
background-color: rgba(0,0,0,0);
-webkit-border-radius: 80px;
}
/* 鼠标滑过的轨道颜色 */
::-webkit-scrollbar:hover {
background-color: rgba(0, 0, 0, 0.09);
}
::-webkit-scrollbar-thumb:vertical {
background: rgba(0,0,0,0.61);
-webkit-border-radius: 80px;
}
/* 鼠标滑过的滚动条样式 */
::-webkit-scrollbar-thumb:vertical:hover {
background: rgba(0,0,0,0.61);
-webkit-border-radius: 80px;
}
/* 鼠标点击滚动条之后的样式 */
::-webkit-scrollbar-thumb:vertical:active {
background: rgba(0,0,0,0.61);
-webkit-border-radius: 80px;
}
/*Try this*/
其他
/*滚动条轨道*/
.scrollbar-track {
position: absolute;
right: 0;
top: 0;
width: 5px;
height: 100%;
background-color: #f2f2f2;
border-radius: 2.5px;
}
/*滚动条滑块*/
.scrollbar-thumb {
position: absolute;
right: 0;
top: 0;
width: 5px;
height: 50px;
background-color: #333;
border-radius: 3px;
cursor: pointer;
}