实现模态返回顶部按钮

Materialize modal back to top button

我有一个来自 Materialise 的模态,我想在用户关闭模态时让模态回到顶部。

模态图像:

我尝试像这样获取滚动值:

console.log("Scroll Top: " + modalContent.scrollTop);
console.log("Offset: " + modalContent.offsetTop);

控制台:

Scroll Top: 229
Offset: 0

我以为我可以覆盖 scrollTop 值,但是当我喜欢时:

document.querySelector(".modal-content").scrollTop = 0;

模态没有任何变化(模态没有滚动到顶部)。

当我尝试记录当前位置时:

console.log(document.querySelector(".modal-content").scrollTop)

每当我滚动 trough 模态时,它总是 returns 零。 我希望当用户单击关闭时,模态将滚动回顶部。我错过了什么吗?

模态:

<div id="team-modal" class="modal modal-fixed-footer margin-top-50">
  <div class="modal-content">
    <div class="card-panel teal modal-scroll">
      <h4 class="white-text light center modal-mark">Team Detail</h4>
      <hr>
      <div class="center">
        <img class="modal-flag-image" src="./assets/images/not-found.svg" alt="Country Flag">
      </div> <!-- center -->
      <div class="center">
        <!-- Some long content here -->
      </div> <!-- center -->
    </div> <!-- card-panel teal-->
  </div> <!-- modal-content -->
  <div class="modal-footer">
    <a class="waves-effect waves-light btn indigo accent-4">Save Team</a>
    <a class="waves-effect waves-light btn red close-modal-btn">Close</a>
  </div> <!-- modal-footer -->
  </div> <!-- modal modal-fixed-footer -->

关闭按钮事件侦听器:

let modalClose = document.querySelector(".close-modal-btn");
modalClose.addEventListener("click", function(e) {
  e.preventDefault();
  document.querySelector(".modal-content").scrollTop = 0;
});

有同样的问题,为我工作:

let element = document.getElementById('scrollTo');

element.scrollIntoView({ behavior: 'smooth', block: 'nearest', inline: 'start' });

方式1.如果你使用materializecss和vanilla Js:

const scrollDemo = document.querySelector("#modal1");
scrollDemo.addEventListener("scroll", event => {
console.log('Scroll Top:', scrollDemo.scrollTop);
console.log('Scroll Left:', scrollDemo.scrollLeft);
}, { passive: true });

scrollDemo.scrollTop = 0;

方式2.如果你使用vuejs和materializecss那么:

<div id="modal1" class="modal" @click="openModal">
   .....
</div>


//In Vue put
Vue({
  methods: {
    scrollUp() {
      console.log('Hello I´m  the  onOpenEnd callback :)');
      let content = document.getElementById("modal1")
                   .getElementsByClassName("modal-content")[0];
      content.scrollTop = 0;
     },
     openModal(){
      //Use callback options modal
      let elem = document.querySelector('#modal1');
      var instance = M.Modal.init(elem,{ onOpenEnd: this.scrollUp });
      instance.open();
    }

  }
});