// 页面加载完毕事件
window.onload = function () {
// 滑动效果 执行函数
left_scroll();
}
//v1位父盒子 v2为子盒子
// v1为父盒子的class类名 书写时记得加引号 left_scroll("father","children")
function left_scroll(v1,v2) {
// 1获取 必要的节点 (即父盒子)
var a = document.querySelector("."+v1+"");
console.log(a.offsetHeight);
console.log(v2);
// 获取移动的元素(通常的做法是 让子盒子在父盒子里面移动 并且子的高度大于父(看实际情况))
var moveNode = document.querySelector("."+v2+"");
console.log(moveNode);
console.log(document.getElementsByClassName('v1')[0]);
// 获取移动的元素的高度
var moveNodeHeight = moveNode.offsetHeight;
// 要移动元素的 父盒子的高度
var moveNodeparentHeight = document.querySelector("."+v2+"").offsetHeight;
console.log("子盒子高度"+moveNodeHeight);
console.log("父盒子高度"+moveNodeparentHeight);
// 计算移动的范围 因为 往上移动个是 y负方向 所有 这里 是减去 而不是加
var minDistance = moveNodeparentHeight - moveNodeHeight ;
console.log("可移动的距离"+minDistance);
var maxDistance = 0;
// 定义变量 用来 标示 吸附的 距离
var delayDistance = 150;
// console.log('最小值'+minDistance);
// console.log('最大值'+maxDistance);
// 定义一些变量 记录 距离
// 起始值
var startY = 0;
// 移动值
var moveY = 0;
// 总的移动距离
var distanceY = 0
// 将 重复的代码 进行封装
var startTransition = function () {
moveNode.style.transition = 'all .5s';
}
var endTransition = function () {
moveNode.style.transition = '';
}
var setTransform = function (distance) {
moveNode.style.transform = 'translateY('+distance+'px)';
}
moveNode.addEventListener('touchstart',function(event){
startY = event.touches[0].clientY;
})
moveNode.addEventListener('touchmove',function(event){
moveY = event.touches[0].clientY - startY;
// 判断 是否满足 移动的条件
if ((moveY+distanceY)>(maxDistance+delayDistance)) {
// 修正 moveY
moveY = 0;
distanceY = maxDistance+delayDistance;
// 为什么是减法 因为 往上移动 是负值 要比最小值 还要更小
}else if((moveY+distanceY)<(minDistance-delayDistance)){
// 修改 moveY
moveY = 0;
distanceY = minDistance-delayDistance;
}
console.log(distanceY);
// 关闭 过渡效果
// moveNode.style.transition = '';
endTransition();
// 移动
// moveNode.style.transform = 'translateY('+(moveY+distanceY)+'px)';
setTransform(moveY+distanceY);
})
moveNode.addEventListener('touchend',function(event){
// 修改移动的总距离
distanceY+=moveY;
// 吸附回去 判断 吸附的方位
if (distanceY>maxDistance) {
distanceY = maxDistance;
}else if(distanceY<minDistance){
distanceY = minDistance;
}
// 吸附回去
// 移动
// moveNode.style.transition ='all .5s';
startTransition();
// moveNode.style.transform = 'translateY('+(distanceY)+'px)';
setTransform(distanceY);
})
}
滑动效果 简单封装(js文件)
最新推荐文章于 2023-08-09 16:40:29 发布