如何将具有平滑动画的scrollIntoView转换为Promise?

Vis*_*dev 0 javascript angular

我必须scrollIntoView顺利地完成某个特定的元素,然后再做某事。

例子

element.scrollIntoView({behavior: 'smooth'}).then(() => {
    // Do something here
})
Run Code Online (Sandbox Code Playgroud)

我知道不能以这种方式完成,因为本机scrollIntoView不会返回 Promise。但是,我怎样才能实现这样的目标呢?

顺便说一句,我正在使用 Angular 7。因此,如果有任何指令可以帮助我实现这一目标,那就太好了。

Fed*_*one 5

您可以使用原型,我认为这可以解决您的问题,而无需下载任何 npm 软件包

/* Extends Element Objects with a function named scrollIntoViewPromise
*  options: the normal scrollIntoView options without any changes
*/

Element.prototype.scrollIntoViewPromise = function(options){

  // "this" refers to the current element (el.scrollIntoViewPromise(options): this = el)
  this.scrollIntoView(options);
  
  // I create a variable that can be read inside the returned object ({ then: f() }) to expose the current element 
  let parent = this;
  
  // I return an object with just a property inside called then
  // then contains a function which accept a function as parameter that will be execute when the scroll ends 
  return { 
    then: function(x){
      // Check out https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API for more informations  
      const intersectionObserver = new IntersectionObserver((entries) => {
        let [entry] = entries;
        
        // When the scroll ends (when our element is inside the screen)
        if (entry.isIntersecting) {
        
          // Execute the function into then parameter and stop observing the html element
          setTimeout(() => {x(); intersectionObserver.unobserve(parent)}, 100)
        }
      });
      
      // I start to observe the element where I scrolled 
      intersectionObserver.observe(parent);
    }
  };
}


element.scrollIntoViewPromise({behavior: "smooth"}).then(()=>console.log("EHI!"));
Run Code Online (Sandbox Code Playgroud)

我创建了一个例子。我知道这不是一个有角度的应用程序,但它是一个很好的起点。您只需要实现它(如果您使用打字稿,您必须创建一个使用新函数扩展 Element 的接口)。