在mousedown mousemove上移动背景位置朝向鼠标移动方向(左/右)

时间:2013-08-06 21:45:31

标签: jquery

请你看看这个JSFIDDLE LINK让我知道如何在mousedown mousemove上动画背景位置拖动鼠标移动方向(左或右)

如您所见,我想添加一个功能,让用户可以向左或向右单击动画图像。

我有

$(document).ready(function () {
 var cp=parseFloat($('.cycle').css('background-position'));
 $('.cycle').stop().animate({'background-position': cp+2000}, 20000); 
 $('.cycle').mouseover(function() {
                                     $('.cycle').stop(); 
     }); 
});

2 个答案:

答案 0 :(得分:0)

所以这就是我如何做到的......

HTML

<div class="cycle">
    <div class="left"></div>
    <div class="right"></div>
</div>

附加CSS

.cycle div
{
    height: 100%;
    width: 50%;
    float: left;
    opacity: 0.5;
}

    .cycle div.left
    {
        background-color: red;
    }
    .cycle div.right
    {
        background-color: blue;
    }

这里的想法是我们有2个子<div>元素,它们占据父元素宽度的50%。这意味着我们可以为每个子div分配一个不同的事件,以便向左或向右滚动,具体取决于哪个具有mouseover

修订JQuery

 $(document).ready(function () {
     loopDeLoop();

     $('.cycle .left').mouseover(function () {
         loopDeLoop("left");
     });

     $('.cycle .right').mouseover(function () {
         loopDeLoop("right");
     });
 });

 function loopDeLoop(direction) {
     var cp = parseFloat($('.cycle').css('background-position'));

     var move = 2000;

     if (direction == "left") {
         move = -2000;
     }

     $('.cycle').stop().animate({
         'background-position': cp + move
     }, 20000);
 }

JSfiddle: http://jsfiddle.net/gvee/n558U/3/

答案 1 :(得分:0)

我创造了更多的东西,希望有所帮助:

<强> LIVE DEMO

 $(function () {                // DOM ready

     var _mX = 0;               // (old Mouse Position) to define if mouse mover right or left
     var mDown = false;         // Mousedown flag
     var $cycle = $('.cycle');  // cache your elements!


     // Storing your animation in a function will help you to reset it once you do mouseleave
     function loop(){
        $cycle.stop().animate({ backgroundPosition: "+=20"}, 500, "linear", loop);
     }
     loop(); // start it!



     $cycle.on('mousedown mouseup',function(e){
         mDown ^= 1;    // 1/0  (Toggle our mDown flag)
     }).hover(function (e) {
         return e.type=="mouseenter"? $(this).stop() : loop() ;  // loop again on mouseleave 
     }).mousemove(function(e){
         var mX = e.clientX;
         var px = _mX > mX ? "-=4" : "+=4"; // Conditional Operator in action    
         if(mDown){ // only if we have a mouseDown flag (1/0 used as boolean)
             $cycle.css({backgroundPosition: px});
         }
         _mX = mX; // reset old mouse position to new one
     });

 });