当div已经可见时,如何在单击另一个按钮时阻止动画运行

时间:2015-07-16 14:02:20

标签: jquery angularjs

我疯了,因为我无法看到这个逻辑失败的地方。

我有这个指令逻辑:

movies.directive('detailsBox', ['$timeout', function($timeout) {

  return {
    restrict: 'A',
    link: function(scope, element, attrs) {

      var current, 
          previous;

      element.on('click', function() {

        if (!current) {
          current = $(this).data('index');
        }
        else {
          previous = current;
          current = $(this).data('index');
        }

        if (current === previous || previous === undefined) {

          // Add a delay so the images 
          // have a chance to load the first time it runs
          $timeout(function() {
            $('.details-box').slideToggle(function() {
              $('.details-box .toggle').fadeToggle();
            });
          }, 300);
        }

      });

    }
  }
}]);

还有三个按钮:

<button data-details-box data-index="1">1</button>
<button data-details-box data-index="2">2</button>
<button data-details-box data-index="3">3</button>

这些按钮中的每一个都会切换包含一些内容的div:

<div class="details-box">
  <div class="toggle">Some content</div>
</div>

如果我点击按钮nr 1,然后按钮nr 2或3,则不应运行任何动画,因为细节框已经可见。

如果我点击按钮nr 1然后再次按nr 1,动画应该运行,因此关闭详细信息框。

问题是当我点击按钮nr 1然后按钮nr 2或3时动画正在运行。它不应该。

1 个答案:

答案 0 :(得分:1)

我认为这里有两个问题。首先......指令不了解前一个指令并在其他指令中应用变量。您需要将它们链接到公共范围。

scope: {
  current: '=current',
  previous: '='
},

在你的HTML中......

<button data-details-box data-index="1" current="current" previous="previous">1</button>
<button data-details-box data-index="2" current="current" previous="previous">2</button>
<button data-details-box data-index="3" current="current" previous="previous">3</button>

其次,我相信你需要在你的element.on调用中使用范围。$ apply()。

scope.$apply(scope.previous = scope.current);

这是一个工作的掠夺者,可以做我想你想要的事情。我不确定你想要的初始条件......

http://plnkr.co/edit/bu34bNSe6yHXCA9SQEUC?p=preview

这就是你要找的东西吗?

相关问题