您的位置:首页 > Web前端 > JavaScript

38、JavaScript的运动----分享到侧边栏

2016-06-20 16:13 393 查看
1、“分享到”侧边栏
    1.1  传三个参数的函数(运动对象的id,速度,目标点)
<!DOCTYPE html>
<html>

<head>
<meta charset="UTF-8">
<title></title>
<style>
#div1 {
width: 100px;
height: 200px;
background: #CCC;
position: absolute;
/*用于隐藏*/
left: -100px;
}

#div1 span {
width: 20px;
height: 60px;
line-height: 20px;
text-align: center;
left: 100px;
top: 70px;
background: yellow;
position: absolute;
}
</style>
<script type="text/javascript">
window.onload = function() {
var oDiv = document.getElementById('div1');
oDiv.onmouseover = function() {
startMove('div1', 10, 0);
}
oDiv.onmouseout = function() {
startMove('div1', -10, -100);
}
}
var timer = null;
/**
* 运动框架的实现
* @param {Object} objId 要运动的对象的id
* @param {Object} iSpeed 运动的速度
* @param {Object} iTarget 运动的目标点
*/
function startMove(objId, iSpeed, iTarget) {
var oDiv = document.getElementById(objId);
clearInterval(timer);
timer = setInterval(function() {
if (oDiv.offsetLeft == iTarget) {
clearInterval(timer);
} else {
oDiv.style.left = oDiv.offsetLeft + iSpeed + 'px';
}
}, 30);
}
</script>
</head>

<body>
<div id="div1">
<span>分享到</span>
</div>
</body>

</html>

    1.2  传两个参数的函数(运动对象的id,目标点)
             – 通过目标点,计算速度值
<!DOCTYPE html>
<html>

<head>
<meta charset="UTF-8">
<title></title>
<style>
#div1 {
width: 100px;
height: 200px;
background: #CCC;
position: absolute;
left: -100px;
}

#div1 span {
width: 20px;
height: 60px;
line-height: 20px;
text-align: center;
left: 100px;
top: 70px;
background: yellow;
position: absolute;
}
</style>
<script type="text/javascript">
window.onload = function() {
var oDiv = document.getElementById('div1');
oDiv.onmouseover = function() {
startMove('div1', 0);
}
oDiv.onmouseout = function() {
startMove('div1', -100);
}
}
var timer = null;
/**
* 实现运动的框架
* @param {Object} objID  要运动的对象的id
* @param {Object} iTarget 运动的目标点
*/
function startMove(objID, iTarget) {
var oDiv = document.getElementById(objID);
clearInterval(timer);
timer = setInterval(function() {
var iSpeed = 0;
/**
* 通过目标点,来计算运动的速度大小
*/
if (oDiv.offsetLeft < iTarget) {
iSpeed = 10;
} else {
iSpeed = -10;
}
if (oDiv.offsetLeft == iTarget) {
clearInterval(timer);
} else {
oDiv.style.left = oDiv.offsetLeft + iSpeed + 'px';
}
}, 30);
}
</script>
</head>

<body>
<div id="div1">
<span>分享到</span>
</div>
</body>

</html>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息