亚洲激情专区-91九色丨porny丨老师-久久久久久久女国产乱让韩-国产精品午夜小视频观看

溫馨提示×

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
凤台县| 滦平县| 南靖县| 手游| 托克逊县| 盐津县| 嵊州市| 渭南市| 郎溪县| 肃南| 读书| 环江| 澳门| 桦南县| 三台县| 西乌| 迭部县| 和龙市| 武邑县| 鄂尔多斯市| 象山县| 绥滨县| 河北省| 应用必备| 文成县| 房山区| 苏州市| 河东区| 吉木萨尔县| 徐州市| 青铜峡市| 花莲市| 诸城市| 佳木斯市| 隆化县| 乐业县| 扎赉特旗| 张家口市| 湖南省| 丰台区| 韶山市|