在线观看不卡亚洲电影_亚洲妓女99综合网_91青青青亚洲娱乐在线观看_日韩无码高清综合久久

鍍金池/ 問答/HTML5  網(wǎng)絡(luò)安全/ angular2+ 兩個(gè)div雙向滾動(dòng)的優(yōu)化

angular2+ 兩個(gè)div雙向滾動(dòng)的優(yōu)化

兩個(gè)div雙向滾動(dòng)的優(yōu)化

附上未優(yōu)化代碼:
html:

<div #left (scroll)="scroll($event,'right')">
</div>
<div #right (scroll)="scroll($event,'left')">
</div>

ts:

 @ViewChild('left') left: ElementRef;
 @ViewChild('right') right: ElementRef;
scroll(e, position) {
    this[position].nativeElement.scrollTop = e.target.scrollTop;
    this[position].nativeElement.scrollLeft = e.target.scrollLeft;
  }

這樣的結(jié)果就是在設(shè)置scrollTopscrollLeft的時(shí)候會(huì)觸發(fā)目標(biāo)domscroll函數(shù)導(dǎo)致頻繁調(diào)用,具體表現(xiàn)就是滾動(dòng)卡頓(鼠標(biāo)滑輪滾動(dòng))

搜到的jquery答案是這樣:

//HTML代碼
<div id="test_Left" onScroll="moveUp_Left();" ></div>
<div id="test_Right"onScroll="moveUp_Right();"  ></div>

//JS代碼
var timer = null;

//左側(cè)DIV的滾動(dòng)事件
function moveUp_Left()
{
    //先刪除右側(cè)DIV的滾動(dòng)事件,以免自動(dòng)觸發(fā)
    $("#test_Right").removeAttr("onScroll");

    //正常設(shè)值,同步兩個(gè)DIV的滾動(dòng)幅度
    $("#test_Right").scrollTop($("#test_Left").scrollTop());
    
    //取消延遲預(yù)約?!局攸c(diǎn)】鼠標(biāo)滾動(dòng)過程中會(huì)多次觸發(fā)本行代碼,相當(dāng)于不停的延遲執(zhí)行下面的預(yù)約
    clearTimeout(timer);

    //延遲恢復(fù)(預(yù)約)另一個(gè)DIV的滾動(dòng)事件,并將本預(yù)約返回給變量[timer]
    timer = setTimeout(function() {
        $("#test_Right").attr("onScroll","moveUp_Right();");
    }, 300 );
}

//右側(cè)DIV的滾動(dòng)事件(原理同上)
function moveUp_Right()
{
    $("#test_Left").removeAttr("onScroll");
    $("#test_Left").scrollTop($("#test_Right").scrollTop());
    clearTimeout(timer);
    timer = setTimeout(function() {
        $("#test_Left").attr("onScroll","mymoveUp_UI03_Left();");
    }, 300 );
}

親測(cè)可行,求問在angular2以上版本怎么去實(shí)現(xiàn)類似效果。

回答
編輯回答
有點(diǎn)壞

既然都用angular2了,處理這種情況當(dāng)然要考慮用rxjs來做了。
rxjs是可以通過監(jiān)聽dom事件來創(chuàng)建一個(gè)observable的。
同時(shí)Observable也提供了Api, 比如debounceTime,distinctUntilChanged 都可以減少對(duì)dom的頻繁修改,提升滑動(dòng)效果。

leftScroll: Subscription = null;
rightScroll: Subscription = null;

this.leftScroll= Observable.fromEvent(this.leftDiv, 'scroll')
            .distinctUntilChanged()
            .debounceTime(500)
            .subscribe((event: Event) => {
                this.handleScroll(this.leftDiv);
            });
this.rightScroll= Observable.fromEvent(this.rightDiv, 'scroll')
            .distinctUntilChanged()
            .debounceTime(500)
            .subscribe((event: Event) => {
                this.handleScroll(this.rightDiv);
            });

rxjs

2017年10月15日 15:10