簡體   English   中英

Angular-jQuery:將jQuery放在單獨的文件中並得到錯誤“無法讀取未定義的屬性” top”

[英]Angular-jQuery : Putting jQuery in a separate file and getting error 'Cannot read property 'top' of undefined'

我有一個基於AngularJS的項目,但我嘗試使用jQuery代碼以使粘性側欄正常工作,當我將代碼放在Plunkr上時,一切正常 ,但是我不知道為什么在我的項目上不工作,實際上我有兩個問題,這是第一個問題。

第二個問題:如果我將jQuery代碼放在<script></script>標記內的同一html文件中,則一切正常。 問題是當我將該代碼移到一個單獨的文件時,瀏覽器控制台出現錯誤Cannot read property 'top' of undefined

這是HTML:

  <div class="col-md-3" id="sidebar">

    <div>

      <div class="panel">
        <div class="panel-group">
         ...
            </accordion-group>
          </accordion>
        </div>
      </div>

    </div>

  </div>

這是jQUery:

$(function() {
  var offset = $('#sidebar').offset(),
      topPadding = 85;
  $(window).scroll(function() {
    if ($(window).scrollTop() > offset.top) {
      $('#sidebar').stop().animate({
        marginTop: $(window).scrollTop() - offset.top + topPadding
      });
    } else {
      $('#sidebar').stop().animate({
        marginTop: 50
      });
    }
  });
});

記得檢查我的Plunkr

還請記住,只有將代碼包含在HTML文件中,該代碼才能正常工作,但是一旦將jQuery代碼放入新文件中,就會出現錯誤。

在嘗試使用jquery函數之前,請確保已調用jquery文件。 您是否可以在Chrome中查看源代碼並查看jquery文件? 如果不是,則您的導入有問題。

實際上我只是意識到發生了什么,您需要做的只是設置一個angular.element(document).ready(function(){...} ,出現此錯誤的原因是因為DOM尚未完全加載。最后,我做了一個Angular Directive以獲得更好的方法

所以:

angular.module('myApp', [])
.directive('sticky', function($document) {
  return {
    restrict: 'A',
    link: function(scope, element, attrs) {
      angular.element(document).ready(function() {
        var offset = element.offset(),
            topPadding = 85;
        $document.scroll(function() {
          if ($document.scrollTop() > offset.top) {
            element.stop().animate({
              marginTop: $document.scrollTop() - offset.top + topPadding
            });
          } else {
            element.stop().animate({
              marginTop: 0
            });
          };
        });
      });
    }
  };
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM