首页 > 为什么下面的代码仅仅在safari中有动画效果

为什么下面的代码仅仅在safari中有动画效果

http://runjs.cn/detail/946emle3


删除 JS 代码。
更改 HTML 为

<div class="container" onclick="this.classList.toggle('change')">
    <div class="bar1"></div>
    <div class="bar2"></div>
    <div class="bar3"></div>
</div>

已测 Chrome 、IE 11 、Edge 。均测试通过。


查看源码:

<div class="container" onclick="animate(this)">
    <div class="bar1"></div>
    <div class="bar2"></div>
    <div class="bar3"></div>
</div>
<style>
...
</style>
<script>
    function animate(x) {
        x.classList.toggle("change");
    }
</script>

将函数名 animate 改变为其他,如 a ,页面在所有页面上都是可用的。

因为在内联事件中,是以this(当前Element)作为 当前对象 来执行js的。

下面的两个代码是等价的:

<div id="div" onclick="fun(this)">a</div>
<script>
function fun(x){
    console.log(x);
}
</script>
<div id="div" onclick="fun(this)">a</div>
<script>
  document.getElementById('div').addEventListener('click', 
    function(){
      with(this){
          console.log(x);
      }
    }, false);
</script>

回到最上面的代码,使用 function animate(){} 注册的函数,相当于注册在 window 上,即 window.animate = function(){}

但 onclick 事件中调用 animate,会先在当前对象中找 animate 方法。 此时当前对象为 Element。所以调用的是当前对象的 Eelement 的 animate 方法。

chrome等浏览器,是有 Element.prototype.animate 方法的。而safari 浏览器中没有此方法。

原始代码可以改为:

<div class="container" onclick="classList.toggle('change')">
    <div class="bar1"></div>
    <div class="bar2"></div>
    <div class="bar3"></div>
</div>

或者

<div class="container" onclick="window.animate(this)">
    <div class="bar1"></div>
    <div class="bar2"></div>
    <div class="bar3"></div>
</div>
<script>
    function animate(x) {
        x.classList.toggle("change");
    }
</script>
【热门文章】
【热门文章】