jQuer配合CSS3实现背景图片动画

HTML部分:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>displayOrder</title>
    <meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1, maximum-scale=1">
</head>
<body>
<div id="topDiv">
    <!-- 顶部图片 -->
    <div class="_img" >
        <img src="./images/img_title.png" alt="图片">
    </div>
</div>
</body>
</html>

css部分:

/*--begin--*/
._topDiv0{
    width: 100%;
    background: url("../images/bg_img.png") no-repeat 0 0;
    background-size: 100%;
    padding-top: 30px;
    position: relative;
    animation: mymove 8s infinite;
    -webkit-animation: mymove 8s infinite;
    /*Safari and Chrome*/
}
._topDiv1{
    width: 100%;
    background: url("../images/bg_img.png") no-repeat 0 0;
    background-size: 100%;
    padding-top: 30px;
    position: relative;
    animation: mymove1 8s infinite;
    -webkit-animation: mymove1 8s infinite;
    /*Safari and Chrome*/
}


/*CSS3 定义动画 Internet Explorer 9 以及更早的版本不支持 animation 属性*/
@keyframes mymove {
    from {background: url("../images/bg_img.png") no-repeat right top;}
    to {background: url("../images/bg_img.png") no-repeat left top;}
}
/*Safari and Chrome*/
@-webkit-keyframes mymove {
    from {background: url("../images/bg_img.png") no-repeat right top;}
    to {background: url("../images/bg_img.png") no-repeat left top;}
}

@keyframes mymove1 {
    from {background: url("../images/bg_img.png") no-repeat left top;}
    to {background: url("../images/bg_img.png") no-repeat right top;}
}
/*Safari and Chrome*/
@-webkit-keyframes mymove1 {
    from {background: url("../images/bg_img.png") no-repeat left top;}
    to {background: url("../images/bg_img.png") no-repeat right top;}
}


._img{
    width: 100%;
    height: auto;
}
._img>img{
    width: 100%;
    height: auto;
}

jQuery部分:

var direction = 0;// 方向标识,0代表向左,1代表向右。
    //动画执行
    function animationChange() {
        $("#topDiv").removeClass("_topDiv"+direction);
        switch (direction){
            case 0:direction=1;
            break;
            default:direction=0;
        }
        $("#topDiv").addClass("_topDiv"+direction);
        window.setTimeout(animationChange,7500);
    }
    animationChange();

注:本例子没有提供jQuery文件,需要另外引入jQuery文件才能看效果。

另:CSS3 定义动画 Internet Explorer 9 以及更早的版本不支持 animation 属性

如有什么问题或者更好的建议,诚挚欢迎提出来,本人将虚心接受。

谢谢阅读!

原文地址:https://www.cnblogs.com/kingchan/p/7170788.html