整理下初学时做过的js基础编程题目和大家分享以下,如果大家觉得有用,别忘了点一下赞哦
JS运动
实现JS拖拽
效果展示:抖音视频链接
index.html
首先,我写是考虑三个部分
第一部分:运动函数:让拖拽元素运动,通过事件源对象的 e.pageX
和 e.pageY
属性 取得鼠标点击位置,用固定定位position:fixed
改变 left
和 top
属性 使其运动,考虑拖拽部分的移动范围,用判断限制 left
和 top
值的范围 。
第二部分:运动控制函数:声明一个 lock
变量,值为true
,监听拖拽原始的父级的 mousedown
事件,如果事件源对象的 e.target
时拖拽元素,则允许运动lock = false
,通过监听拖拽原始的父级的 mousemove
事件拿到事件事件源对象的 e.pageX
和 e.pageY
属性,执行运动函数,最后监听拖拽原始的父级的 mousemove
事件,禁止运动lock = false
,监听拖拽原始的父级的 mouseleave
事件,鼠标离开父级,禁止运动lock = false
。
第三部分:考虑到窗口大小变化时,更新视口大小的宽高window.innerWidth
和window.innerHeight
。
<div class="mainArea"></div>
<script src="./index.js"></script>
<script>
new MyDrag(".mainArea","body")//拖拽元素 拖拽元素的父参照物
</script>
index.js
class MyDrag{
constructor(el,wrap){
this.el = document.querySelector(el)//拖拽元素
this.wrap = document.querySelector(wrap)//拖拽元素父参照物
this.width = window.innerWidth;//可视窗口大小
this.height = window.innerHeight;//可视窗口大小
this.init()
}
init(){
this.resize()
this.update()
}
update(){//运动控制函数
// 实现 控制变量
let lock = true;
this.wrap.addEventListener("mousedown",(e)=>{
// 如果点击的是拖拽元素 允许运动
e.target.className === this.el.className && (lock = false)
},false)
this.wrap.addEventListener("mousemove",(e)=>{
// 允许运动时,实现运动函数,实现运动
!lock && this.changeFn(e.pageX,e.pageY)
},false)
this.wrap.addEventListener("mouseup",()=>{
// 鼠标抬起时,禁止运动
lock =true
},false)
this.wrap.addEventListener("mouseleave",()=>{
// 鼠标移出父参照物,禁止运动
lock = true
})
}
changeFn(x,y){//拖拽元素的运动函数
let elW = this.el.offsetWidth ;//获取拖拽元素的宽度
let elH = this.el.offsetHeight;//获取拖拽元素的高度
//限制拖拽 left 属性 x 值的范围
if(x> this.width - 0.5*elW){
x = this.width - elW
}else if (x < 0.5*elW){
x = 0
}else{
x -= 0.5*elW
}
//限制拖拽 top 属性 y 值的范围
if(y> this.height - 0.5*elH){
y = this.height - elH
}else if (y < 0.5*elH){
y = 0
}else{
y -= 0.5*elH
}
// 通过拖拽元素的固定定位上的 left 和 top 属性实现运动
this.el.style.left = x + "px";
this.el.style.top = y + "px";
}
resize(){//获取可视区域的宽高的函数
let self = this
window.addEventListener("resize",function(){
//窗口大小改变时,更新宽高
self.width =window.innerWidth
self.height = window.innerHeight
},false)
}
}
index.css
body{
margin:0;
position:relative;
background-color: #ccc;
height:100vh
}
.mainArea{
width: 100px;
height: 100px;
background: url("./xiaoliu.jpg") no-repeat center/cover;
border-radius:20px;
position: fixed;
left:0;
right:0;
}
这里扩展下 body 元素的冷知识点
- body的背景
如果HTML元素有背景,body元素正常(背景覆盖画布)
如果HTML元素没背景,body元素的背景覆盖画布
如果我只给body 加上宽高和背景
body {
width: 100px;
height: 100px;
background-color: #ccc;
}
会出现我的宽高是正确的,但是背景是覆盖整个窗口,这就比较奇怪了
我给html标签加个背景后,再看看
html {
background-color: #999;
}
body {
width: 100px;
height: 100px;
background-color: #ccc;
}
body的背景又正常了