Angular 5-使用按钮进行水平滚动

时间:2019-03-08 05:09:54

标签: angular

我已经在角度应用程序中实现了卡的水平滚动。滚动工作正常。但是,我想让用户也可以通过单击“左”和“右”按钮向左或向右滚动。每个按钮只能滚动自己的msgCardDeck

这是我在StackBlitz上的代码:

https://stackblitz.com/edit/angular-atnq4z

这是我的打字稿,可滚动显示,但不起作用。如果有办法做到,将不胜感激。

// Scroll Left if there is anything to scroll
  scrollLeft() {
    document.querySelector('div.msgCard').scrollLeft -= 500;
  }

// Scroll Right if there is any area to scroll

  scrollRight() {
    document.querySelector('div.msgCard').scrollLeft += 500;
  }

2 个答案:

答案 0 :(得分:1)

尝试此解决方案。

将事件对象作为函数的参数传递。

// necessary changes for ts.
 scrollLeft(e) {
    let wrapper = e.srcElement.closest('.msgCardScrollWrapper');
    wrapper.querySelector('.msgCardDeck').scrollLeft -= 500;
 }

 scrollRight(e) {
    let wrapper = e.srcElement.closest('.msgCardScrollWrapper');
    wrapper.querySelector('.msgCardDeck').scrollLeft += 500;
 }
 // necessary changes for html.
 <div class="msgCardNavRightButton" (click) = "scrollRight($event)">
    <button class="btn btn-primary">Right</button>
  </div>

 <div class="msgCardNavLeftButton" (click) = "scrollLeft($event)">
    <button class="btn btn-primary">Left</button>
 </div>

答案 1 :(得分:0)

Hardik回答中的以下增强对我有用:

// necessary changes for ts.
     scrollLeft(e) {
        // find parent element; which has scrollable div.
        let wrapper = e.srcElement.closest('.msgCardScrollWrapper');
        let totalWidth = wrapper.querySelector('.msgCardDeck').clientWidth;
        // apply value to scrollable div.
        wrapper.querySelector('.msgCardDeck').scrollLeft -= totalWidth/2;
     }

     scrollRight(e) {
        let wrapper = e.srcElement.closest('.msgCardScrollWrapper');
        // find parent element; which has scrollable div.
        let totalWidth = wrapper.querySelector('.msgCardDeck').clientWidth;
        // apply value to scrollable div.
        wrapper.querySelector('.msgCardDeck').scrollLeft += totalWidth/2;
     }

     // necessary changes for html.
     <div class="msgCardNavRightButton" (click)="scrollRight($event)">
        <button class="btn btn-primary">Right</button>
      </div>

     <div class="msgCardNavLeftButton" (click)="scrollLeft($event)">
        <button class="btn btn-primary">Left</button>
     </div>