[程式碼&DEMO] [HackMD完整筆記]
實作滑鼠點擊後,能夠左右移動捲軸的效果。
STEP1 取得頁面元素與宣告變數
const slider = document.querySelector('.items');
let isDown = false;
let startX;
let scrollLeft;
STEP2 滑鼠按下事件
slider.addEventListener('mousedown', (e) => {
isDown = true;
slider.classList.add('active');
startX = e.pageX - slider.offsetLeft;
scrollLeft = slider.scrollLeft;
});
STEP3 滑鼠移出事件
slider.addEventListener('mouseleave', () => {
isDown = false;
slider.classList.remove('active');
});
STEP4 滑鼠按鍵放開事件
slider.addEventListener('mouseup', () => {
isDown = false;
slider.classList.remove('active');
});
STEP5 滑鼠移動事件
slider.addEventListener('mousemove', (e) => {
if(!isDown) return; //stop the fn running
e.preventDefault();
const x = e.pageX - slider.offsetLeft;
const walk = (x - startX);
slider.scrollLeft = scrollLeft - walk;
});