【问题标题】:Uncaught TypeError: 1 argument required, but only 0 present...But my function takes no arguments?未捕获的类型错误:需要 1 个参数,但只有 0 个存在……但是我的函数没有参数?
【发布时间】:2016-12-11 13:43:43
【问题描述】:

我试图使一个空的 div 具有宽度和高度以及背景颜色在屏幕上移动调用一个函数 onclick。它不需要任何论据。但是当我单击元素时,它说:“未捕获的类型错误:无法在'元素'上执行'动画':需要 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>

【问题讨论】:

  • 我在 Chrome v52 中没有收到错误

标签: javascript animation onclick arguments typeerror


【解决方案1】:

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

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

【讨论】:

  • 第二个是错误的。如果你使用属性 onclick 你需要调用函数。
【解决方案2】:

尝试将 animate 函数重命名为其他名称。好像你调用的不是你的函数,而是元素 box1animate 方法。

【讨论】:

  • 谢谢。那行得通。我“打勾”并投票赞成你的答案。我能看到它。但我不确定其他人是否可以。它说类似...“因为我的声誉低于 15,您的反馈将被记录,但不会在屏幕上实时显示”。对不起……
  • @xxkaiwaxx 没关系)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-18
  • 2018-02-16
相关资源
最近更新 更多