在IE / FireFox中工作但不在chrome中的HTML代码

时间:2016-12-11 06:43:57

标签: javascript html

这是一个非常简单的代码,我想尝试并开始运行,因为我想学习一些JavaScript基础知识。该代码适用于Internet Explorer和Firefox,但不适用于chrome。我觉得我必须错过一些非常愚蠢的东西。



var frame = 2;
function animate(){

if(frame == 1){
    frame = frame + 1;
    document.getElementById("animate").src = "walking1.png";
}
else if (frame == 2){
    frame = frame + 1;
    document.getElementById("animate").src = "walking2.png";
}
else{
    frame = 1;
    document.getElementById("animate").src = "walking3.png";
}
}

<p> clicking the button will change the image.</p>

<img id="animate" src="walking1.png">

<button onclick="animate()">click me to animate</button>
&#13;
&#13;
&#13;

使用的图片保存在同一文件夹中。

1 个答案:

答案 0 :(得分:5)

animate同时用作功能名称和ID,这会导致它无法在Chrome中使用。

另外,提及in this post,单独使用名称为animate的功能也可能无法在Chrome中运行,具体取决于其实现方式。 (见下面的注释)

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script type="text/javascript">
var frame = 2;
function animatee(){

if(frame == 1){
    frame = frame + 1;
    document.getElementById("animate").src = "http://placehold.it/100";
}
else if (frame == 2){
    frame = frame + 1;
    document.getElementById("animate").src = "http://placehold.it/100/f00";
}
else{
    frame = 1;
    document.getElementById("animate").src = "http://placehold.it/100/00f";
}
}
</script>
</head>
<body>
  <p> clicking the button will change the image.</p>

  <img id="animate" src="http://placehold.it/100/0f0">

  <button onclick="animatee();">click me to animate</button>

</body>
</html>

注意:

guest271314进行的观察表明,如果onclick处理程序没有内联,则问题不存在

window.onload = function() {

  var frame = 2;

  function animate() {
    console.log("animate called")
    if (frame == 1) {
      frame = frame + 1;
      document.getElementById("animatee").src = "http://placehold.it/100x100";
    } else if (frame == 2) {
      frame = frame + 1;
      document.getElementById("animatee").src = "http://placehold.it/200x200";
    } else {
      frame = 1;
      document.getElementById("animatee").src = "http://placehold.it/100/00f";
    }
  }
  
  document.querySelector("button").onclick = animate;
}
<p> clicking the button will change the image.</p>

<img id="animatee" src="http://placehold.it/100/0f0">

<button>click me to animate</button>

为他们的辩护Kaiido提供了规范:https://html.spec.whatwg.org/#named-access-on-the-window-object

Knu对此错误报告做出了贡献:https://www.w3.org/Bugs/Public/show_bug.cgi?id=11960

相关问题