我正在制作一个简单的javascript动画,我使用
clientX来确定动画对象的位置,但我得到了上面的错误。我在这做错了什么?
这是JS代码:
(function() {
var pos = 0;
var timer;
var anim = {
time: 100,
obj: null,
init: function () {
anim.obj = document.querySelector('#ball');
anim.obj.style.left = 0 + 'px';
anim.cord();
console.log(document.querySelector('.coordonnee').pageX);
},
cord: function (e) {
if ( parseInt(anim.obj.style.left) >= parseInt(document.body.offsetWidth - anim.obj.offsetWidth) ) {
anim.animBack();
} else {
anim.obj.style.left = parseInt( anim.obj.style.left) + 1 + 'px';
timer = setTimeout(anim.cord, 0.5);
}
anim.myCord(anim.obj.event);
},
animBack: function() {
if ( parseInt(anim.obj.style.left) <= 0 ) {
anim.cord()
} else {
anim.obj.style.left = parseInt( anim.obj.style.left) - 1 + 'px';
timer = setTimeout(anim.animBack, 0.5);
}
},
myCord: function(e) {
var mx = e.clientX;
var y = e.clientY;
console.log(anim.obj.mx);
}
}
anim.init();
})(window);
HTML代码:
<!DOCTYPE html>
<html>
<head>
<title>JS animation</title>
<style type="text/css">
#ball {
width: 50px;
height: 50px;
background: #ff45ce;
border-radius: 50%;
-webkit-border-radius: 50%;
position: relative;
left: 0;
}
</style>
</head>
<body>
<div id="ball" ></div>
<script type="text/javascript" src="js/animation.js"></script>
</body>
</html>
提前感谢您的帮助!
答案 0 :(得分:0)
我认为你传递的事件是空的
anim.object.event is null in this function
anim.myCord(anim.obj.event);
答案 1 :(得分:0)
我在此 fiddle 中试用了您的代码。
此处出现的错误是:TypeError: e is undefined
var mx = e.clientX;
那是因为,您的事件为空或未定义。为此目的重新定义你的逻辑。