CSS 动画:animation和transition

本文介绍了如何使用CSS3中的animation和transition属性来创建动画效果。通过实例演示了动画的关键帧定义方法及过渡效果的应用场景,包括鼠标悬停和点击事件触发的样式变化。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

animation

animation使用时必须配合@keyframes

<!DOCTYPE html>
<html>
<head>
    <style> 
        div 
        {
            width:100px;
            height:100px;
            background:red;
            position:relative;
            animation:mymove 5s infinite;
            -webkit-animation:mymove 5s infinite; /*Safari and Chrome*/
        }

        @keyframes mymove
        {
            from {left:0px;}
            to {left:200px;}
        }

        @-webkit-keyframes mymove /*Safari and Chrome*/
        {
            from {left:0px;}
            to {left:200px;}
        }
    </style>
</head>
    <body>

    <p><strong>注释:</strong>Internet Explorer 9 以及更早的版本不支持 animation 属性。</p>

    <div></div>

</body>
</html>

运行结果可见:http://www.w3school.com.cn/tiy/t.asp?f=css3_animation

transition

<!DOCTYPE html>
<html>
<head>
    <style> 
    div
    {
        width:100px;
        height:100px;
        background:blue;
        transition:width 2s;
        -moz-transition:width 2s; /* Firefox 4 */
        -webkit-transition:width 2s; /* Safari and Chrome */
        -o-transition:width 2s; /* Opera */
    }

    div:hover
    {
        width:300px;
    }
    </style>
</head>
<body>

<div></div>

<p>请把鼠标指针移动到蓝色的 div 元素上,就可以看到过渡效果。</p>

<p><b>注释:</b>本例在 Internet Explorer 中无效。</p>

</body>
</html>

示例:http://www.w3school.com.cn/tiy/t.asp?f=css3_transition

除了使用hover,我们也可以这样写:

<!DOCTYPE html>
<html>
<head>
    <style> 
    div
    {
        width:100px;
        height:100px;
        background:blue;
        transition:width 2s;
        -moz-transition:width 2s; /* Firefox 4 */
        -webkit-transition:width 2s; /* Safari and Chrome */
        -o-transition:width 2s; /* Opera */
    }
    .widthnew{
      width:300px;
    }

    </style>
</head>
<body>

<div onclick="changewidth()"></div>

</body>
<script type="text/javascript">
    function changewidth(){
        console.log("console");
        document.querySelector("div").className = 'widthnew';
    }
</script>
</html>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值