You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

AngularJS:改写窗口Resize监控指令以追踪指定元素宽度

Modified Directive to Track Element Width on Window Resize

Absolutely, you can tweak that directive to focus on a specific element's width instead of the window's. Here's a rewritten version that keeps the resize event listener but shifts its focus to your target element—plus I added some flexibility to make it even more useful:

app.directive('monitorElementResize', ['$window', function ($window) {
    return {
        link: link,
        restrict: 'A',
        scope: {
            // Optional: specify a target element via selector if needed
            targetElement: '@?'
        }
    };

    function link(scope, element, attrs) {
        // Decide which element to track: specified target or the directive's host element
        var targetEl = scope.targetElement 
            ? angular.element(document.querySelector(scope.targetElement)) 
            : element;

        // Core function to calculate and handle the element's width
        function updateElementWidth() {
            // Choose the width property that fits your needs:
            // offsetWidth = content + padding + border
            // clientWidth = content + padding (no border/scrollbar)
            // scrollWidth = full content width (including overflow)
            var elementWidth = targetEl[0].offsetWidth;
            
            // Replace this with your custom logic
            console.log('Updated element width:', elementWidth);
            
            // Example: Pass width to parent scope if needed
            // scope.$emit('elementResized', elementWidth);
        }

        // Calculate initial width on directive load
        updateElementWidth();

        // Listen for window resize events
        var resizeHandler = angular.element($window).on('resize', function () {
            // Trigger Angular's digest cycle since resize is a native browser event
            scope.$apply(updateElementWidth);
        });

        // Clean up the event listener when the directive is destroyed to avoid memory leaks
        scope.$on('$destroy', function () {
            angular.element($window).off('resize', resizeHandler);
        });
    }
}]);

Key Changes & Features:

  • Purpose-Focused Naming: Renamed to monitorElementResize to clearly reflect what it does.
  • Flexible Targeting: Use the optional target-element attribute to track a different element (e.g., <div monitor-element-resize target-element="#main-content"></div>). If no target is set, it defaults to the element the directive is attached to.
  • Width Property Options: Pick between offsetWidth, clientWidth, or scrollWidth depending on whether you need to include borders, padding, or overflow content.
  • Initial Calculation: Runs once on directive initialization to get the element's starting width, not just on resize.
  • Cleanup: Removes the resize event listener when the directive is destroyed to prevent memory leaks.

How to Use:

  1. Track the directive's host element:

    <div monitor-element-resize class="my-container">...</div>
    
  2. Track a separate element:

    <div monitor-element-resize target-element="#sidebar">...</div>
    <div id="sidebar">...</div>
    

If you need to bind the width to your controller, add a two-way binding to the scope:

scope: {
    targetElement: '@?',
    elementWidth: '='
}

Then update updateElementWidth to set scope.elementWidth = elementWidth;, and use it in your template:

<div monitor-element-resize element-width="containerWidth"></div>
<p>Current container width: {{containerWidth}}px</p>

This setup will run your logic every time the window resizes, but now it uses your specified element's width instead of the window's.

内容的提问来源于stack exchange,提问作者mBo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 09:30:40