【问题标题】:Using Modernizr and jQuery to Animate if CSS3 Transitions Don't Exist如果 CSS3 过渡不存在,使用 Modernizr 和 jQuery 制作动画
【发布时间】:2011-08-31 05:29:33
【问题描述】:

如果不支持 CSS3,有没有办法结合使用 Modernizr 和 jQuery 来启用类似于过渡的功能?我现在做的是这样的……

<div class="hoverable">
 <p>This div changes both width and height on hover</p>
</div>

CSS是

.hoverable {
 height: 100px;
 width: 2000px;
 transition: height .5s, width .5s;
}

.hoverable:hover {
 height: 200px;
 width: 100px;
}

如果不支持 CSS3 过渡,我目前只是使用 Modernizr 使 div 默认处于悬停状态。如果不支持 CSS3,有没有办法使用 Modernizr 来触发 jQuery 动画?如果不是 jQuery,那么我也可以使用自定义动画,但我也不知道该怎么做。

【问题讨论】:

  • 您可以使用 $.animate() 重现效果,尽管有些效果可能非常慢(滞后)。或者您可以在旧浏览器中禁用某些效果,因为通常视觉效果不是那样重要
  • 这就是我目前正在做的事情。 (我的意思是禁用效果)

标签: javascript jquery css transitions


【解决方案1】:

自己解决了这个问题。我的做法是这样的

<!doctype html>
<html>
    <head>
        <title>Modernizr + jQuery Testing</title>
        <script type="text/javascript" src="modernizr.js"></script>
        <script type="text/javascript" src="jquery.js"></script>
        <script type="text/javascript">
        if(!Modernizr.csstransitions) { // Test if CSS transitions are supported
            $(function() {
                $('#js').hover(function(){
                    $(this).animate({width:'50px',height:'50px'},{queue:false,duration:500});
                }, function(){
                    $(this).animate({width:'100px',height:'100px'},{queue:false,duration:500});
                });
            });
        }
        </script>
        <style type="text/css">
            body {
                margin: 0;
                padding: 0;
            }
            div {
                border: 1px solid red;
                height: 100px;
                margin: 25px auto;
                width: 100px;
            }
            #css {
                transition: height .5s, width .5s;
                -khtml-transition: height .5s, width .5s;
                -moz-transition: height .5s, width .5s;
                -o-transition: height .5s, width .5s;
                -webkit-transition: height .5s, width .5s;
            }
            #css:hover {
                height: 50px;
                width: 50px;
            }
        </style>
    </head>

    <body>
        <div id="js">
            JS
        </div>
        <div id="css">
            CSS
        </div>
    </body>
</html>

效果很好。 CSS 仅在新浏览器中设置动画(因为这是它唯一可以使用的地方),而 JS 仅在旧浏览器中设置动画。如果你使用这个脚本,你可以从http://www.modernizr.com/ 获得modernizr 和从http://www.jquery.com/ 获得jQuery(当然)。

【讨论】:

    【解决方案2】:

    你可以使用:

    if(!Modernizr.csstransitions) { // 测试是否支持 CSS 过渡 $('#myDiv').bind({ 鼠标输入:函数(){ $(this).animate({ 宽度:1000, 身高:1000 }, 1000); }, 鼠标离开:函数(){ $(this).animate({ 宽度:100, 身高:100 }, 1000); } }); }

    【讨论】:

    • 这看起来很有效。我会在一个小时左右试试。
    • 试过这个,但不能让它工作。我应该把它放在&lt;head&gt; 以外的地方吗?
    • 您能否发布您所做的不同之处以便我们知道?
    猜你喜欢
    • 2012-04-18
    • 1970-01-01
    • 2013-05-16
    • 2014-05-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-09
    • 2013-03-20
    相关资源
    最近更新 更多