目录
学习来源: https://www.bilibili.com/video/BV1HJ41147DG
PC端网页特效一链接:https://blog.youkuaiyun.com/qq_45645902/article/details/105876298
5、mouseenter 和 mouseover 的区别
- 当鼠标移动到元素上时就会触发 mouseenter 事件
- 类似 mouseover,它们两者之间的差别是
- mouseover 鼠标经过自身盒子会触发,经过子盒子还会触发
- mouseenter 只会经过自身盒子触发(鼠标经过盒子后,只要不离开盒子,即使是父盒子,都不会触发)
- 之所以这样,就是因为 mouseenter 不会冒泡
- 跟 mouseenter 搭配的鼠标离开 mouseleave 同样不会冒泡
6、动画函数封装
动画实现原理
核心原理:通过定时器 setInterval() 不断移动盒子位置。
示例
实现步骤
- 获得盒子当前位置
- 让盒子在当前位置加上1个移动距离
- 利用定时器不断重复这个操作
- 加一个结束定时器的条件
- 注意此元素需要添加定位,才能使用 element.style.left
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
div {
/* 添加定位,为了使用 element.style.left */
position: absolute;
left: 0;
width: 100px;
height: 100px;
background-color: red;
}
</style>
</head>
<body>
<div></div>
<script>
// div.offsetLeft 获得盒子当前位置
var div = document.querySelector('div');
var timer = setInterval(function () {
if (div.offsetLeft >= 400) {
// 停止动画 本质是停止定时器
clearInterval(timer);
}
div.style.left = div.offsetLeft + 1 + 'px';
}, 30);
</script>
</body>
</html>
简单动画函数封装
函数需要传递2个参数,动画对象和移动到的距离
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
div {
position: absolute;
left: 0;
width: 100px;
height: 100px;
background-color: red;
}
span {
position: absolute;
left: 0;
top: 200px;
display: block;
width: 150px;
height: 150px;
background-color: skyblue;
}
</style>
</head>
<body>
<div></div>
<span>我是一颗小小的石头</span>
<script>
// 简单动画函数封装:obj 目标对象、target 目标位置
function animate(obj, target) {
var timer = setInterval(function () {
if (obj.offsetLeft >= target) {
// 停止动画 本质是停止定时器