javascript Angular 通过 id 获取元素的偏移量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33877153/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 16:59:34  来源:igfitidea点击:

Angular get offset of element by id

javascriptjqueryangularjs

提问by Ore

I try to set the navbar li object to active when i currently watch the corresponding section. In other words: When scrolling through my page (single page with multiple sections), the section i'm watching should be highlighted in the navbar.

当我当前观看相应部分时,我尝试将导航栏 li 对象设置为活动状态。换句话说:当滚动浏览我的页面(单页有多个部分)时,我正在观看的部分应该在导航栏中突出显示。

I already got the scrolling position via directive. Where I fail is to trigger ng-class on the .nav ul li.

我已经通过指令获得了滚动位置。我失败的地方是在 .nav ul li 上触发 ng-class。

<li class="" ng-class="{'active': $parent.scrollPos > document.getElementById('something').offset()}">
   <a class="" ng-click="isCollapsed = true" href="#something" du-smooth-scroll>Something</a>
</li>

I doesn't make any difference when I use

我使用时没有任何区别

ng-class="{'active': $parent.scrollPos > angular.element('#something').offset()}"

How do I get the distance from document-top of any element?

如何获得与任何元素的文档顶部的距离?

Thanks a lot.

非常感谢。

PS: I use jQuery (not lite)!

PS:我使用 jQuery(不是精简版)!

EDITHow it works (Thanks to @Sharikov Vladislav): On body I use the "PageCtrl":

编辑它是如何工作的(感谢@Sharikov Vladislav):在身体上我使用“PageCtrl”:

<body id="page-top" class="index bg-default" ng-app="previewApp" ng-controller="PageCtrl">

which looks like that:

看起来像这样:

angular.module('previewApp')
  .controller('PageCtrl', function($scope, $element) {
    $scope.scrollPos = 0;
    $scope.getOffset = function (elementId) {
      var element = $element.find(elementId);      
      return element.offset().top;
    };
  });

Right after the body I use a span

在身体之后,我使用了跨度

<span scroll-position="scrollPos"></span>

to initialise my "scrollPosition"-directive, which allows me to access the current scroll position over the $scope.scrollPos in PageCtrl. Directive:

初始化我的“scrollPosition”指令,它允许我在 PageCtrl 中的 $scope.scrollPos 上访问当前滚动位置。指示:

angular.module('previewApp')
  .directive('scrollPosition', function ($window) {
    return {
      scope: {
        scrollPos: "=scrollPosition"
      },
      link: function (scope, element, attrs) {
        var windowElement = angular.element($window);
        var handler = function () {
          scope.scrollPos = windowElement.scrollTop();
        }
        windowElement.on('scroll', scope.$apply.bind(scope, handler));
        handler();
      }
    };
  });

In my .nav ul li looks like the following. The "- 150" is for a more acurate highlighting.

在我的 .nav ul li 看起来像下面这样。“- 150”用于更精确的突出显示。

<div class="navbar-collapse" uib-collapse="isCollapsed" id="menu-center">
   <ul class="nav navbar-nav navbar-right">
       <li class="hidden">
           <a href="#page-top"></a>
       </li>
       <li ng-class="{'active': $parent.scrollPos > $parent.getOffset('#section1') - 150 && $parent.scrollPos < $parent.getOffset('#section2') - 150}">
         <a ng-click="isCollapsed = true" href="#section1" du-smooth-scroll>Section1</a>
       </li>
       <li ng-class="{'active': $parent.scrollPos > $parent.getOffset('#section2') - 150 && $parent.scrollPos < $parent.getOffset('#section3')}">
         <a ng-click="isCollapsed = true" href="#section2" du-smooth-scroll>Section2</a>
       </li>                 
    </ul>
</div>

I hope this helps somebody out there who is struggling over the same problem like me. Greets

我希望这可以帮助那些像我一样为同样的问题而苦苦挣扎的人。问候

回答by Sharikov Vladislav

No no no. Wrong! You should not use jQuery, when you are using AngularJS. Inject $elementservice in your controller:

不不不。错误的!当您使用 AngularJS 时,您不应该使用 jQuery。$element在您的控制器中注入服务:

JavaScript:

JavaScript:

myCtrl.$inject = ['$scope', '$element']; 
function myCtrl($scope, $element) {
 var element = $element.find('#someId');
 $scope.getOffset = function () {
  return element.offset().top;
 };
}

HTML:

HTML:

<div ng-class='{ "active": getOffset() > xxx }'></div>

You have not to use $(document)or purejQuery in AngularJS at all.

您根本不必在 AngularJS使用$(document)jQuery 。

回答by Rich

you could try something like:

你可以尝试这样的事情:

$(document).scrollTop() > document.getElementById('something').offset().top

(caveat - I havent' time to test right now - but will later)

(警告 - 我现在没有时间测试 - 但稍后会)

I would also suggest saving all your element's Y positions to refer to rather than doing this calculation each time

我还建议保存所有元素的 Y 位置以供参考,而不是每次都进行此计算

回答by Mukesh Kumar Bijarniya

Use .offset() to get the distance between an element and the top of the document:

使用 .offset() 获取元素与文档顶部之间的距离:

angular.element(("li .active").offset().top