见注释里的提问,问题还是给某个事件调用函数加不加括号的问题;
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>practice</title>
<style type="text/css">
*{margin:0px;padding:0px;}
#div1 {position:relative;left:-200px;width:200px;height:200px;margin-top:50px;background-color: pink;}
#share{background-color:lightblue;width:20px;height:50px;position: absolute;left:200px;top:75px;}
</style>
<script type="text/javascript">
window.onload=function(){
var div1=document.getElementById("div1");
/*div1.onmouseover=startMove; */ /*不加括号,就是正常的,鼠标放上,开始移动;*/
div1.onmouseover=startMove(); /*为什么加了括号之后,一打开就开始移动,鼠标不放上去也是移动的;*/
};
var timer=null;
function startMove(){
var div1=document.getElementById("div1");
timer=setInterval(
function(){
if(div1.offsetLeft==0){clearInterval(timer)}
else {div1.style.left=div1.offsetLeft+10+'px'}}
,30);
}
</script>
</head>
<body>
<div id="div1">
<span id="share">分享</span>
</div>
</body>
</html>