<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
#p1{
width: 200px;
height: 200px;
background: red;
position: absolute;
top: 50px;
left: 0px;
}
</style>
<script>
var timer=null;
function startmove()
{
var op=document.getElementById('p1');
timer=setInterval(function(){
if(op.offsetLeft==300)
{
clearInterval(timer);
}
else
{
op.style.left=op.offsetLeft+10+'px';
}
}, 30);
}
</script>
</head>
<body>
<button onclick="startmove()">开始</button>
<p id="p1">
</p>
</body>
</html>
这里的if里面的offsetleft换成style.left为什么就不行
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
因为 style.left返回的时候后面会加上"px" 没办法判断。
try
看到了没,这就是相同一个p的left和offsetLeft的值,两者不一定相等,而且用left会取到你设置的样式值,比如100px或者40%;
left是获取该dom元素的css,所以如果是固定值则带上'px',可读写
offsetLeft 是一个只读属性,返回当前元素左上角相对于 HTMLElement.offsetParent 节点的左边界偏移的像素值。
很给力,
function startMove()
前端菜鸟:http://www.bird100.cn