Jquery CSS背景图像旋转

时间:2016-05-07 11:11:31

标签: javascript jquery html css rotation

我有一个主div,后台设置为它(齿轮),通过javascript(滚动)旋转。在里面我有另一个div(停止旋转),我想停止旋转。我只希望背景旋转,而不是内容。

如何阻止第二个div旋转?或者有更简单的解决方法吗?

这是我的JSFiddle

HTML:

<body>


 <div class="gear">
     <div class="stop-rotate">
         <h1 style="color:white">random text</h1>
     </div>
 </div>

</body>

CSS:

body{
    height: 1000px;
    background: blue;
}

.gear{
    background: url("http://i.imgur.com/zZ3fMuh.png");
    width: 101px;
    height: 102px;
}

使用Javascript:

$(function() {
    var rotation = 0, 
        scrollLoc = $(document).scrollTop();
    $(window).scroll(function() {
        var newLoc = $(document).scrollTop();
        var diff = scrollLoc - newLoc;
        rotation += diff, scrollLoc = newLoc;
        var rotationStr = "rotate(" + rotation + "deg)";
        $(".gear").css({
            "-webkit-transform": rotationStr,
            "-moz-transform": rotationStr,
            "transform": rotationStr,
        });
    });
})

如何阻止第二个div旋转?

1 个答案:

答案 0 :(得分:1)

您可以使第二个div以相反方向旋转。

$(function() {
    var rotation = 0, rotation2=0,
        scrollLoc = $(document).scrollTop();
    $(window).scroll(function() {
        var newLoc = $(document).scrollTop();
        var diff = scrollLoc - newLoc;
        rotation += diff, scrollLoc = newLoc;
        rotation2 -= diff, scrollLoc = newLoc;
        var rotationStr = "rotate(" + rotation + "deg)";
        var rotationStr2 = "rotate(" + rotation2 + "deg)";

        $(".gear").css({
            "-webkit-transform": rotationStr,
            "-moz-transform": rotationStr,
            "transform": rotationStr,
        });
        $(".stop-rotate").css({
            "-webkit-transform": rotationStr2,
            "-moz-transform": rotationStr2,
            "transform": rotationStr2,
        });

    });
})

这是JSFiddle:https://jsfiddle.net/3xcqjcsr/