<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>单个div变宽</title>
<style type="text/css">
#div1{
width:100px;
height: 50px;
background-color: red;
position: absolute;
left: 50px;
}
</style>
<script type="text/javascript">
window.onload=function(){
var oDiv=document.getElementById('div1');
oDiv.onmouseover=function(){
startMove(300);
}
oDiv.onmouseout=function(){
startMove(100);
}
};
function startMove(iTarget){
var oDiv=document.getElementById('div1');
var timer=null;
var txt=document.getElementById('txt');
clearInterval(timer);
timer=setInterval(function(){
var iSpeed=(iTarget-oDiv.offsetWidth)/10;
iSpeed=iSpeed>0?Math.ceil(iSpeed):Math.floor(iSpeed);
if (oDiv.offsetWidth==iTarget) {
clearInterval(timer);
}
else{
oDiv.style.width=oDiv.offsetWidth+iSpeed+'px';
}
txt.value=oDiv.offsetWidth+'px';
},30)
}
</script>
</head>
<body>
<input type="text" name="txt" id="txt" value="" />
<div id="div1">
</div>
</body>
</html>
这是我的代码,有时候会正常,但是大部分时候会出现不正常情况,宽度卡在半中腰,不上不下的。请大神指点指点!万分感谢!!!
<html>
<head>
<meta charset="UTF-8">
<title>单个div变宽</title>
<style type="text/css">
#div1{
width:100px;
height: 50px;
background-color: red;
position: absolute;
left: 50px;
}
</style>
<script type="text/javascript">
window.onload=function(){
var oDiv=document.getElementById('div1');
oDiv.onmouseover=function(){
startMove(300);
}
oDiv.onmouseout=function(){
startMove(100);
}
};
function startMove(iTarget){
var oDiv=document.getElementById('div1');
var timer=null;
var txt=document.getElementById('txt');
clearInterval(timer);
timer=setInterval(function(){
var iSpeed=(iTarget-oDiv.offsetWidth)/10;
iSpeed=iSpeed>0?Math.ceil(iSpeed):Math.floor(iSpeed);
if (oDiv.offsetWidth==iTarget) {
clearInterval(timer);
}
else{
oDiv.style.width=oDiv.offsetWidth+iSpeed+'px';
}
txt.value=oDiv.offsetWidth+'px';
},30)
}
</script>
</head>
<body>
<input type="text" name="txt" id="txt" value="" />
<div id="div1">
</div>
</body>
</html>
这是我的代码,有时候会正常,但是大部分时候会出现不正常情况,宽度卡在半中腰,不上不下的。请大神指点指点!万分感谢!!!
window.onload = function () {
var oDiv = document.getElementById('div1'); oDiv.onmouseover = function () {
startMove(300);
} oDiv.onmouseout = function () {
startMove(100); } };
var timer = null;////////变为全局的,要不动画未完成你移动出会生成另外一个timer,一个+一个-那不是动来动去的了,来回移动多次会一致生成计时器,耗尽内存
function startMove(iTarget) {
var oDiv = document.getElementById('div1');
///var timer = null;///
var txt = document.getElementById('txt'); clearInterval(timer);
timer = setInterval(function () {
var iSpeed = (iTarget - oDiv.offsetWidth) / 10; iSpeed = iSpeed > 0 ? Math.ceil(iSpeed) : Math.floor(iSpeed); if (oDiv.offsetWidth == iTarget) {
clearInterval(timer);
}
else {
oDiv.style.width = oDiv.offsetWidth + iSpeed + 'px';
}
txt.value = oDiv.offsetWidth + 'px';
}, 30)
}