gpt4 book ai didi

javascript - AngularJS:观察高度变化的更好方法

转载 作者:IT王子 更新时间:2023-10-29 03:10:56 31 4
gpt4 key购买 nike

我遇到了旧的可变高度导航问题:顶部的 position: fixes 导航和下面的 margin-top: $naviHeight 内容。当异步加载数据时,导航可以改变高度,因此内容的边距必须随之改变。

我希望它是独立的。因此,没有加载数据的代码,而是仅在涉及的 html 元素/指令中。

目前我正在使用这样的计时器在 AngularJS 1.2.0 中执行此操作:

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

scope.$on( 'heightchange', function( ev, newHeight ){

elem.attr( 'style', 'margin-top: ' + (58+newHeight) + 'px' );
} );
}
}
})

/*
* Checks this element periodically for height changes
*/
.directive( 'emHeightSource', ['$timeout', function( $timeout ) {

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

function __check(){

var h = elem.height();

if( h != scope.__height ){

scope.__height = h;
scope.$emit( 'heightchange', h );
}
$timeout( __check, 1000 );
}
__check();
}
}

} ] )

这有明显的使用计时器的缺点(我觉得有点丑)和在调整导航大小后直到内容被移动有一定的延迟。 p>

有更好的方法吗?

最佳答案

这通过在 emHeightSource 中注册一个 watcher 来实现,每个 $digest 都会调用它。它更新 __height 属性,该属性又在 emHeightTarget 中被监视:

/*
* 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();
} );
}
}

} )

关于javascript - AngularJS:观察高度变化的更好方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19048985/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com