上联:这个需求很简单
下联:怎么实现我不管
横批:明天上线
一、鼠标坐标获取
1、横坐标:clientX
2、纵坐标:clientY
<script>
// onmousemove - 当鼠标移动会触发事件
document.onmousemove = function (e) {
console.log(e.clientX, e.clientY);
};
</script>
二、offset系列属性
1、offsetWidth:用于获取元素的真实宽度,除了margin以外的宽
2、offsetHeight:用于获取元素的真实高度,除了margin以外的高
3、offsetLeft:用于获取元素到定位父盒子之间的左侧距离,当前元素的边框到定位父盒子的边框之间的距离(边框到边框)。
4、offsetTop:用于获取元素到定位父盒子之间的顶部距离,当前元素的边框到定位父盒子的边框之间的距离(边框到边框)。
5、offsetParent:获取定位父盒子
模拟拖拽小案例
<style>
* {
margin: 0;
padding: 0;
}
#box {
width: 100px;
height: 100px;
background-color: pink;
position: absolute;
left: 100px;
top: 120px;
}
</style>
<div id="box"></div>
<script>
var box = document.getElementById('box');
// - 盒子默认不跟随,点击盒子后,让盒子以点击位置跟随
// 1 在点击盒子时,获取鼠标在盒子内的坐标,计算方式:鼠标坐标 - 盒子的左侧距离
// 2 设置真正的拖拽效果:需要将点击分为点下和抬起两种操作,mousedown - 鼠标按键点下后触发,mouseup - 鼠标按键抬起后触发
// - 鼠标按键点下时获取鼠标在盒子内的坐标
box.onmousedown = function (e) {
var x = e.clientX - box.offsetLeft;
var y = e.clientY - box.offsetTop;
// - 鼠标移动,设置跟随
document.onmousemove = function (e) {
box.style.left = e.clientX - x + 'px';
box.style.top = e.clientY - y + 'px';
};
};
// - 鼠标按键抬起,清除跟随效果
box.onmouseup = function () {
// 清除跟随效果
document.onmousemove = null;
};
</script>
三、定时器
1、timeout
timeout定时器,延时定时器
1、参数1:时间到达后执行的操作,函数
参数2:延迟的时间,毫秒单位
返回值:返回当前定时器标识,用于进行清除操作。
var timer = null;
timer = setTimeout(function () {
console.log('这是打印的内容');
}, 3000);
2、清除定时器的方式
参数:定时器的标识id
btn.onclick = function () {
clearTimeout(timer);
};
2、interval
interval定时器 - 间隔定时器
1、设置方式:
参数1:间隔执行的操作代码,函数
参数2:间隔时间,毫秒单位
var timer = null;
timer = setInterval(function () {
console.log('打印了内容');
}, 1000);
2、清除定时器
btn.onclick = function () {
clearInterval(timer);
// 特殊点:两个定时器的清除方式可以互换使用,这个操作没有意义,不推荐这样使用。
// clearTimeout(timer);
};
运动的案例请参考我写的四个轮播图
简单轮播图(1):https://blog.csdn.net/weixin_40589472/article/details/83957670
左右焦点轮播图(2):https://blog.csdn.net/weixin_40589472/article/details/83962253
无缝滚动轮播图(3):https://blog.csdn.net/weixin_40589472/article/details/83962613
完整轮播图(4):https://blog.csdn.net/weixin_40589472/article/details/83988106