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

查看:94
本文介绍了css - 为什么下面的代码仅仅在safari中有动画效果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

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

解决方案

查看源码:

<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>

这篇关于css - 为什么下面的代码仅仅在safari中有动画效果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆