倒數三天,繼續加油!
今日任務: 可以按著往左右拖曳滑動內容
.items {
...
cursor: pointer;
transition: all 0.2s;
transform: scale(0.98);
will-change: transform;
position: relative;
background: rgba(255, 255, 255, 0.1);
font-size: 0;
perspective: 500px;
}
.items.active {
background: rgba(255, 255, 255, 0.3);
cursor: grabbing;
cursor: -webkit-grabbing;
transform: scale(1);
}
const items = document.querySelector('.items');
let isDown = false;
let startX;
let scrollLeft;
items.addEventListener('mousedown', () => (isDown = true));
items.addEventListener('mouseup', () => (isDown = false));
items.addEventListener('mouseleave', () => (isDown = false));
items.addEventListener('mousemove', () => {
if (!isDown) return;//沒有按下去就直接返回
console.log(isDown);
});
const items = document.querySelector('.items');
let isDown = false;
let startX;
let scrollLeft;
items.addEventListener('mousedown', startCoords);
items.addEventListener('mouseup', stopScroll);
items.addEventListener('mouseleave', stopScroll);
items.addEventListener('mousemove', onScroll);
function startCoords(e) {
isDown = true;
items.classList.add('active');
}
function onScroll() {
if (!isDown) return;
console.log(isDown);
}
function stopScroll() {
isDown = false;
items.classList.remove('active');
}
offsetX/offsetY
:以滑鼠到外層容器的左上角為原點(0,0),距離原點的水平/垂直距離。(Day16)
clientX/clientY
:以滑鼠到視窗左上角為原點(0,0),距離原點的水平/垂直距離。
pageX/pageY
:以 滑鼠到HTML Document 文件左上角為原點(0,0),距離原點的水平/垂直距離。
offsetLeft/offsetTop
: 元素本身相對於母元素的水平/垂直距離。(Day13)
Element.scrollLeft
: 元素內容水平滾動的像素數。
items.addEventListener('mousedown', startCoords);
function startCoords(e) {
isDown = true;
items.classList.add('active');
startX = e.pageX - items.offsetLeft;
console.log(startX);
scrollLeft = items.scrollLeft;
}
function onScroll(e) {
if (!isDown) return;
const x = e.pageX - items.offsetLeft;
const move = x - startX;
console.log(move);
}
當滑鼠按住往左拖曳時,畫面要往右滾動,所以要將scrollLeft-滑鼠拖曳位移量
function onScroll(e) {
if (!isDown) return;
const x = e.pageX - items.offsetLeft;
const move = x - startX;
items.scrollLeft = scrollLeft - move;
}
function onScroll(e) {
if (!isDown) return;
const x = e.pageX - items.offsetLeft;
const move = (x - startX) * 3;
items.scrollLeft = scrollLeft - move;
}
今日學習到的:
offsetX/offsetY
:以滑鼠到外層容器的左上角為原點(0,0),距離原點的水平/垂直距離。clientX/clientY
:以滑鼠到視窗左上角為原點(0,0),距離原點的水平/垂直距離。pageX/pageY
:以 滑鼠到HTML Document 文件左上角為原點(0,0),距離原點的水平/垂直距離。offsetLeft/offsetTop
: 元素本身相對於母元素的水平/垂直距離。Element.scrollLeft
: 元素內容水平滾動的像素數。效果連結:連結
參考連結:
Element.scrollLeft
什麼是 clientHeight, clientWidth, offSetHeight, offsetWidth, scrollHeight, scrollWidth, scrollTop, scrollLeft