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

分享代码格式的js书写

2015-12-20 18:07 295 查看
分享代码格式的js书写


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>分享</title>
</head>
<style type="text/css">
body{padding:0;margin:0;}
#n_content{width:200px;background:red;position:relative;top:50px;height:300px;left:-200px;}
#content{width:50px;background:green;position:absolute;top:100px;height:100px;left:200px;}
</style>
<body>
<div id="n_content">
<span id="content">分享</span>
</div>
<script type="text/javascript">
window.onload=function(){
var odiv = document.getElementById("n_content");
odiv.onmouseover = function(){
startMove(0);
}
odiv.onmouseout = function(){
startMove(-200);
}

}
timer=null;
function startMove(iTarget){
clearInterval(timer);
var odiv = document.getElementById("n_content");
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>
</body>
</html>


效果如图:

没有移入之前



移入鼠标之后



知识点:

1. 样式的定位

父级position用relative

自己position用absolute

2.js获取当前元素和两个事件

odiv = document.getElementById(“n_content”);

onmouseover和onmouseout事件

定时器格式

timer=null;

timer=setInterval(function(){

},30);

清除计时器

clearInterval(timer);

获取当前元素的距左的距离

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