91超碰碰碰碰久久久久久综合_超碰av人澡人澡人澡人澡人掠_国产黄大片在线观看画质优化_txt小说免费全本

溫馨提示×

javascript自定義滾動條代碼怎么寫

小億
108
2023-07-31 16:12:11
欄目: 編程語言

要自定義滾動條,你可以使用 CSS 和 JavaScript 來實現。以下是一個簡單的示例代碼:

HTML:

<div class="container">
<div class="content">
<!-- 內容 -->
</div>
</div>

CSS:

.container {
width: 200px;
height: 300px;
overflow: auto;
position: relative;
}
.content {
width: 100%;
height: 1000px;
}
.scrollbar {
position: absolute;
right: 0;
top: 0;
width: 6px;
background-color: #ccc;
border-radius: 3px;
opacity: 0;
transition: opacity 0.3s;
cursor: pointer;
}
.scrollbar:hover {
opacity: 1;
}
.thumb {
background-color: #888;
border-radius: 3px;
width: 100%;
position: absolute;
top: 0;
left: 0;
}

JavaScript:

const container = document.querySelector('.container');
const content = document.querySelector('.content');
const scrollbar = document.createElement('div');
const thumb = document.createElement('div');
scrollbar.classList.add('scrollbar');
thumb.classList.add('thumb');
container.appendChild(scrollbar);
scrollbar.appendChild(thumb);
// 更新滾動條位置
const updateScrollbar = () => {
const contentHeight = content.clientHeight;
const containerHeight = container.clientHeight;
const scrollTop = container.scrollTop;
const scrollRatio = scrollTop / (contentHeight - containerHeight);
const scrollbarHeight = containerHeight * containerHeight / contentHeight;
thumb.style.height = `${scrollbarHeight}px`;
thumb.style.transform = `translateY(${scrollRatio * (containerHeight - scrollbarHeight)}px)`;
};
// 滾動條拖動事件
thumb.addEventListener('mousedown', (e) => {
const startY = e.clientY;
const thumbTop = thumb.getBoundingClientRect().top;
const containerTop = container.getBoundingClientRect().top;
const maxScrollTop = content.clientHeight - container.clientHeight;
const mouseMoveHandler = (e) => {
const deltaY = e.clientY - startY;
const thumbPosition = thumbTop - containerTop + deltaY;
const scrollRatio = thumbPosition / (container.clientHeight - thumb.clientHeight);
container.scrollTop = scrollRatio * maxScrollTop;
};
const mouseUpHandler = () => {
document.removeEventListener('mousemove', mouseMoveHandler);
document.removeEventListener('mouseup', mouseUpHandler);
};
document.addEventListener('mousemove', mouseMoveHandler);
document.addEventListener('mouseup', mouseUpHandler);
});
// 監聽內容滾動事件
container.addEventListener('scroll', updateScrollbar);
// 初始化滾動條
updateScrollbar();

這段代碼會添加一個自定義滾動條到容器 .container 中,并監聽滾動事件更新滾動條的位置。你可以根據需要對 CSS 樣式進行調整來自定義滾動條的外觀和行為。

0
丰台区| 建平县| 乌恰县| 江华| 林周县| 都江堰市| 南澳县| 广宗县| 隆安县| 昌图县| 永新县| 花莲县| 天长市| 韶山市| 东乡族自治县| 遂川县| 象州县| 兴业县| 天峻县| 新平| 体育| 瑞丽市| 夹江县| 绵竹市| 石棉县| 昌邑市| 贺州市| 德兴市| 集贤县| 贡嘎县| 新干县| 博客| 双峰县| 盱眙县| 蓝田县| 梅州市| 闸北区| 澄迈县| 无极县| 陆良县| 塘沽区|