未捕获的TypeError:需要1个参数,但只有0个...但是我的函数没有参数?

时间:2016-08-05 08:04:07

标签: javascript animation onclick arguments uncaught-typeerror

我试图制作一个宽度和高度为空的div,背景颜色在屏幕上移动,调用一个函数onclick。它不需要任何参数。但当我点击它所说的元素时:“未捕获的TypeError:无法在'元素'上执行'animate':需要1个参数,但只有0个存在。我缺少什么?

var container = document.getElementById('container');
var box1 = document.getElementById('box1');
var containerWidth = container.clientWidth;
var box1Width = box1.clientWidth;

function animate() {
    box1.style.left = '0px';
    setTimeout(function() {
        box1.style.transition = 'left 1000ms ease';
        box1.style.left = containerWidth - box1Width + 'px';
    }, 1);
}
body {
    margin: 0;
}

#container {
    position: relative;
    height: 100vh;
    width: 100vw;
    background-color: aqua;
}

#box1 {
    position: relative;
    height: 100px;
    width: 100px;
    left: 0px;
    background-color: yellow;
}
<div id="container">
  <div id="box1" onclick="animate()"></div>
</div>

2 个答案:

答案 0 :(得分:4)

尝试将animate函数重命名为其他内容。好像你称之为不是你的功能,而是animate元素box1的方法。

答案 1 :(得分:0)

首先,使用addEventHandler!不要混用HTML和Javascript!

然后处理程序必须是函数,而不是函数的结果。 因为“animate”是一个函数,“animate()”是无效的。