
實作一個隨著滑鼠點擊左右移動內容的效果。
overflow 改成 hidden 才不會漏出卷軸醜醜的取得外框元素。
設定變數
false
startX
scrollLeft
使用到四種滑鼠事件 mousedown, mouseleave, mouseup, mousemove,外框元素個別綁定事件監聽,即觸發事件。
處理滑鼠點擊事件的變數
mousedown :確定滑鼠被點擊,變數改為 true
mouseleave:確定滑鼠移開畫面,變數改為 false
mouseup:確定滑鼠沒點擊,變數改為 false
mousemove:確認滑鼠有點擊,事件再往下移
if (!isDown) return;
處理滑鼠點擊後的樣式變化
mousedown :增加樣式 class .active
slider.classList.add('active');
mouseleave:移除樣式 class .active
slider.classList.remove('active');
mouseup:移除樣式 class .active
slider.classList.remove('active');
找到滑鼠點擊的 x 軸點位
mousedown :利用 e 找到 起始位置 = e.pageX - 外框.offsetLeft 取得
slider.addEventListener('mousedown', (e) => {
startX = e.pageX - slider.offsetLeft;
console.log(startX);
});
計算移動的距離
mousedown :點擊當下已經被移動的距離
scrollLeft = slider.scrollLeft;
mousemove:
e.perventDefault 停止預設行為
取得移動到的位置 = 點擊到的位置 - 外框移動的距離
const x = e.pageX - slider.offsetLeft;
console.log({ x, startX });
取得移動的距離 = 移動到的位置 - 點擊到的位置 * 3(增加移動時的視覺感)
const move = x - startX
取得更新新的 slider.scrollLeft = 點擊當下已經被移動的距離 - 移動的距離
slider.scrollLeft = scrollLeft - move;
mousedown → touchstart
mousemove → touchmove
mouseup → touchend