不止有offsetLeft,还有offsetTop,和offsetHeight,offsetWidth;
不管是offsetLeft还是offset什么 都是有BUG的地方.那就是它只能获取行间的样式,不能获取非行间的样式,下面有解决方案
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
#div1{
height: 200px;
width: 200px;
background-color: #f00;
position: relative;
left: 200px;
top: 150px;
}
</style>
</head>
<body>
<div id="div1"></div>
<script>
setInterval(function(){
var div1 = document.getElementById('div1');
//让div1的左间距没30毫秒加10px
div1.style.left = div1.offsetLeft+10+'px';
},30);
</script>
</body>
</html>
不管是offsetLeft还是offset什么 都是有BUG的地方.那就是他只能获取行间样式,不能获取非行间的样式.这个就需要用到别的东西来代替
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
#div1{
/* width: 200px; */
height: 200px;
background-color: #f00;
border: 100px solid #000;
width: 200px;
}
</style>
</head>
<body>
<div id="div1"></div>
<script>
// 这样我们不管在不在行间我们都能拿到样式
function getStyle(obj, name){
if(obj.currentStyle){
return obj.currentStyle[name];
}else{
return getComputedStyle(obj, false)[name];
};
};
setInterval (function(){
var div = document.getElementById('div1');
// 重点
var crr = parseInt(getStyle(div,'width'));
div.style.width = crr-2+'px';
},30);
</script>
</body>
</html>