如果上面div的元素 - 设置类“不可见”

时间:2015-06-23 14:31:48

标签: javascript angularjs

我在首页(300像素高度)和ng-repeat中的项目中有Div。 如果元素“Hello World”部分或完全隐藏在top div之下,我需要设置类“no_visible”(每个span元素)。我怎么能这样做?

var app = angular.module('plunker', []);

app
.controller('MainCtrl', function($scope) {
  $scope.name = 'World';
  $scope.items = [];
  for(var i =0; i<100;i++){
    $scope.items.push(i);
  }
})
.directive('trackVisibility', function(){
  function isVisible(el) {
    var rect = el.getBoundingClientRect();
    var clw = (window.innerWidth || document.documentElement.clientWidth);
    var clh = (window.innerHeight || document.documentElement.clientHeight) ;

    // checks if element is fully visible
    //return (rect.top >= 0 && rect.bottom <= clh) && (rect.left >= 0 && rect.right <= clw);

    // checks if part of element is visible
    return (rect.left <= clw && 0 <= rect.right && rect.top <= clh && 0 <= rect.bottom);

  }
  var reg = [];

  function register(element, fn) {
    reg.push([element, fn]);
  }

  function deregister(element) {
    reg = angular.filter(reg, function (item) {
      return item[0] !== element;
    });
  }

  angular.element(window).on('DOMContentLoaded load resize scroll', function () {
    angular.forEach(reg, function (item) {
        item[1](isVisible(item[0]));
    });
  });

    
  return {
    restrict: 'A',
    link: function (scope, element, attrs, controller) {
      register(element[0], function(isVisible){
        scope.$apply(function(){
          scope.isVisible = isVisible;
        })
      });
      scope.$on('$destroy', function(){
        deregister(element);
      })
    }
  };
});
span {
display: block;
height: 30px;
border: 1px solid;
}
<html ng-app="plunker">

  <head>
    <meta charset="utf-8" />
    <title>AngularJS Plunker</title>
    <script>document.write('<base href="' + document.location + '" />');</script>
    <link rel="stylesheet" href="style.css" />
    <script data-require="angular.js@1.2.x" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.17/angular.min.js" data-semver="1.2.16"></script>
    <script src="app.js"></script>
  </head>

  <body ng-controller="MainCtrl">
    
    <div style="height:300px; width:300px; position: fixed; background: #000;">
    </div>
    
    <div style="margin-top:350px; position: absolute;">
    <span style="float:left; clear: both; " ng-repeat="i in items" track-visibility>Hello {{name}} {{isVisible?'yes':'no'}}!</span>
    </div>
    
    
  </body>

</html>

1 个答案:

答案 0 :(得分:0)

(function(){

angular.module('app')

//Each element has to be called "my-element"
.directive('myElement', function(){

  return {

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

      //probably need to perfom this action on a event listener   

      window.on('scroll', function(){
           var top = $el.getBoundingClientRect().top;  
           if(top < 200){
               //Hide me
               element.hide();
           }
      }


     }
  };

});
})();