」工欲善其事,必先利其器。「—孔子《論語.錄靈公》
首頁 > 程式設計 > AngularJS $watch 如何取代動態導航高度調整中的計時器?

AngularJS $watch 如何取代動態導航高度調整中的計時器?

發佈於2024-11-05
瀏覽:427

How Can AngularJS $watch Replace Timers in Dynamic Navigation Height Adjustment?

避免 AngularJS 的高度監視計時器

當導航高度是動態時,AngularJS 程式設計師經常面臨響應式導航的挑戰。這就導致需要調整內容的 margin-top 值以回應導航高度的變化。

以前,使用計時器來偵測導航高度的變化,但這種方法有缺點:使用計時器和調整內容的 margin-top 出現延遲。

幸運的是,有更好的方法:利用 AngularJS 的 $watch 功能。在「emHeightSource」中註冊了一個觀察程序,而不是計時器,該觀察程序在每個 $digest 週期期間被呼叫。觀察者更新 '__height' 屬性。

在'emHeightTarget' 中,另一個觀察者監視'__height' 並相應更新margin-top 值,確保內容的margin-top 平滑變化並與導航同步height.

這裡是使用觀察者的精煉程式碼:

/*
 * Get notified when height changes and change margin-top
 */
.directive( 'emHeightTarget', function() {
    return {
        link: function( scope, elem, attrs ) {

            scope.$watch( '__height', function( newHeight, oldHeight ) {
                elem.attr( 'style', 'margin-top: '   (58   newHeight)   'px' );
            } );
        }
    }
} )

/*
 * Checks every $digest for height changes
 */
.directive( 'emHeightSource', function() {

    return {
        link: function( scope, elem, attrs ) {

            scope.$watch( function() {
                scope.__height = elem.height();
            } );
        }
    }

} )
最新教學 更多>

免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。

Copyright© 2022 湘ICP备2022001581号-3