如何跟踪.animate左位置 [英] How to track .animate left position

查看:122
本文介绍了如何跟踪.animate左位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Hi我有这个JQuery,它将左右移动一个div,当左和右按​​钮,但是我需要它停止当图像位置在0px;

Hi I have this JQuery which will move a div left and right when hovered on the left and right buttons, however I need it to stop when the image position is at 0px;

我当前的代码 - https://jsfiddle.net / 38da9pca / 2 /

My current code - https://jsfiddle.net/38da9pca/2/

$(function() {
    $('#right').on('mouseenter', rscroll);
    $('#left').on('mouseenter', lscroll);
    $('#right, #left').on('mouseleave', function() {
        $('#bg').stop();
    });

    function rscroll() {
        $('#bg').animate({
            left: '-=25'
        }, 10, rscroll);
    }

    function lscroll() {
        $('#bg').animate({
            left: '+=25'
        }, 10, lscroll);
    }
});

但是我似乎不能跟踪 #bg left positon。我累了 .position()。left .offset()。left console.log(); 而不是在滚动时进行不断变化。

However I can't seem to track the #bg left positon. I have tired .position().left and .offset().left and both of them give a static result when console.log(); instead of dymically changing whilst scrolling.

推荐答案


  • 如果是,则不执行任何操作

  • 如果没有,请检查下一个更改是否超过边界


    • 如果会,将只移动剩余距离。

    • 如果没有,请移动 25 像素

    • If it is, do nothing
    • If not, check if the next change is will go past the boundaries
      • If it will, only move by the remaining distance.
      • If it wont, move by 25 pixels

      此外,您应该缓存您的jQuery对象,以便获得更好的性能。

      Also, you should cache your jQuery objects for better performance as I've done here.

      href =https://jsfiddle.net/38da9pca/13/ =nofollow>演示)

      (Demo)

      $(function() {
          var bg = $('#bg'), left, maxLeft, maxRight;
          $('#right').on('mouseenter', rscroll);
          $('#left').on('mouseenter', lscroll);
          $('#right, #left').on('mouseleave', function() {
              bg.stop();
          });
      
          function rscroll() {
              maxRight = (bg.width() - $(window).width()) * -1;
              left = bg.position().left;
              if(left > maxRight) {
                  bg.animate({
                      left: '-=' + (left + 25 > maxRight ? 25 : left)
                  }, 10, rscroll);
              }
          }
      
          function lscroll() {
              maxLeft = bg.width() - $(window).width();
              left = bg.position().left;
              if(left < 0) {
                  bg.animate({
                      left: '+=' + (maxLeft - left > 25 ? 25 : left)
                  }, 10, lscroll);
              }
          }
      });
      

      这篇关于如何跟踪.animate左位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆