使用Modernizr和jQuery实现动画效果,如果CSS3过渡效果不可用

5
有没有一种方法可以结合Modernizr和jQuery来实现类似于CSS3转换效果的功能,如果CSS3不被支持?我目前正在做以下事情...
<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;
}

我目前只是使用Modernizr,如果不支持CSS3过渡效果,则默认使div处于悬停状态。是否有一种方法可以使用Modernizr在不支持CSS3的情况下触发jQuery动画?如果不能使用jQuery,则我也可以使用自定义动画,但我不知道如何做。


你可以使用$.animate()来复制这个效果,尽管有些效果可能会非常缓慢(卡顿)。或者你可以在旧浏览器中禁用一些效果,因为通常视觉效果并不那么重要。 - Ortiga
这就是我目前正在做的事情。(我的意思是禁用效果) - JacobTheDev
2个回答

12

我自己解决了这个问题。我所做的方式是这样的

<!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(当然)。


4

您可以使用:

如果(!Modernizr.csstransitions){ //测试CSS过渡是否受支持
    $('#myDiv')。bind({
        mouseenter:function(){
            $(this).animate({
                宽度:1000,
                高度:1000
            },1000);
        },
        mouseleave:function(){
            $(this).animate({
                宽度:100,
                高度:100
            },1000);
        }
    });
}

那看起来很有效。我大约一个小时后会尝试一下。 - JacobTheDev
尝试过了,但无法使其工作。除了<head>标签之外,我应该将它放在其他地方吗? - JacobTheDev
你能分享一下你做的不同之处,以便我们了解吗? - Paul Sham

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接