本篇文章给大家带来的内容是关于javascript匀速运动实现侧边栏分享效果(代码),有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。
采用offsetLeft(对象距离左边的距离)加固定速度。
采用定时器setInterval和clearInterval
根据当前位置到目标位置是正值还是负值决定运行的速度为正值还是负值。
<!DOCTYPE html>
<html>
<head>
<title>用运动做一个侧边栏分享</title>
<style>
#div1{
width: 150px;
height: 200px;
background: #0f0;
position: absolute;
left: -150px;
}
#div1 span{
position: absolute;
width: 20px;
height: 60px;
line-height: 20px;
background: #00f;
right: -20px;
top: 70px;
}
</style>
<script>
window.onload=function(){
var oDiv=document.getElementById("div1");
oDiv.onmouseover=function(){
startMove(10,0);
}
oDiv.onmouseout=function(){
startMove(-10,-150);
}
}
var timer=null;
function startMove(speed,iTarget){
var oDiv=document.getElementById("div1");
clearInterval(timer);
timer=setInterval(function(){
if(oDiv.offsetLeft==iTarget){
clearInterval(timer);
}else{
oDiv.style.left=oDiv.offsetLeft+speed+"px";
}
},30)
}
</script>
</head>
<body>
<div id="div1">
<span>分享到</span>
</div>
</body>
</html>当我们写好一段代码的时候,我们应该进行测试优化。测试无兼容问题,封装后的移动函数有两个参数,这个时候,我们考虑参数是否可以简化。
比如我们打出租车,我们可以告诉司机目的地,但是我们不必告诉司机以多少速度到目的地,所以,我们可以简化参数为一个参数。具体代码如下。
立即学习“Java免费学习笔记(深入)”;
<!DOCTYPE html>
<html>
<head>
<title>用运动做一个侧边栏分享</title>
<style>
#div1{
width: 150px;
height: 200px;
background: #0f0;
position: absolute;
left: -150px;
}
#div1 span{
position: absolute;
width: 20px;
height: 60px;
line-height: 20px;
background: #00f;
right: -20px;
top: 70px;
}
</style>
<script>
window.onload=function(){
var oDiv=document.getElementById("div1");
oDiv.onmouseover=function(){
startMove(0);
}
oDiv.onmouseout=function(){
startMove(-150);
}
}
var timer=null;
function startMove(iTarget){
var oDiv=document.getElementById("div1");
clearInterval(timer);
timer=setInterval(function(){
var speed=0;
if(oDiv.offsetLeft>iTarget){
speed=-10;
}else{
speed=10;
}
if(oDiv.offsetLeft==iTarget){
clearInterval(timer);
}else{
oDiv.style.left=oDiv.offsetLeft+speed+"px";
}
},30)
}
</script>
</head>
<body>
<div id="div1">
<span>分享到</span>
</div>
</body>
</html>相关推荐:
原生javascript实现匀速运动动画效果_javascript技巧
以上就是javascript匀速运动实现侧边栏分享效果(代码)的详细内容,更多请关注php中文网其它相关文章!
java怎么学习?java怎么入门?java在哪学?java怎么学才快?不用担心,这里为大家提供了java速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号