<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>js基础动画</title>
<style type="text/css">
body,div,span {
margin: 0;
padding: 0;
}
#div1 {
width: 200px;
height: 200px;
background: red;
position: relative;
left: -200px;
top: 0;
}
#div1 span {
width: 20px;
height: 50px;
background: blue;
position: absolute;
left: 200px;
top: 75px;
}
</style>
</head>
<body>
<script>
window.onload = function () {
var oDiv = document.getElementById("div1");
oDiv.onmouseover = function () {
move(0);
}
oDiv.onmouseout = function () {
move(-200);
}
}
var timer = null;
function move(dis) {
clearInterval(timer);
var oDiv = document.getElementById("div1");
timer = setInterval(function () {
var speed = 0;
if (oDiv.offsetLeft > dis) {
speed = -10;
}
else {
speed = 10;
}
if (oDiv.offsetLeft == dis) {
clearInterval(timer);
}
else {
oDiv.style.left = oDiv.offsetLeft + speed + 'px';
}
}, 30)
}
</script>
<div id="div1">
<span id="share">分享</span>
</div>
</body>
</html>
setInterval(函数,毫秒) 定时器
onmouseover 鼠标移入
onmouseout 鼠标移出
object.style.left 修改left
object.offsetLeft 当前的left
object.style.left=object.offsetLeft+num'px',在手机端可引入rem.js修改代码中px-》rem实现简单自适应
clearInterval 清除定时器(不清除会导致每次鼠标移进或移出时同时执行两个三个或者更多定时器)
借鉴思想,函数的封装与speed的判断。
本文介绍了使用JavaScript创建基础动画的技巧,通过setInterval实现定时器,结合onmouseover和onmouseout事件监听鼠标移入移出。利用对象的style.left属性和offsetLeft属性动态调整元素位置,实现页面左侧的分享动画效果。在移动端,可通过引入rem.js将px转换为rem实现自适应。同时,文中强调了clearInterval的重要性,以避免多个定时器同时运行造成的问题,并提出函数封装和speed判断的思考。
354

被折叠的 条评论
为什么被折叠?



