首页 > 解决方案 > 如何在没有滚动行为的情况下转到特定部分/没有滚动行为的 scrollIntoView() 的任何替代方法?

问题描述

我正在尝试创建到特定部分的页面重定向,即我想转到页面上的特定锚 div 而没有滚动行为。但是,我在 URL 中有一个用于分页的查询字符串,因此 #id 方法对我来说失败了。我尝试了“scrollIntoView()”,但它包含页面滚动行为,这是不受欢迎的。请问是否有任何替代解决方案来解决这个问题?

我在前端使用 Vue,在后端使用 Codeigniter。这是我的代码:

        mounted() {
            // anchorPageToProductList
            if (this.isOnQuery) {
                console.log('isOnQuery');
                this.scrollToProductList();
            } else {
                console.log('isNotOnQuery');
            }
            
        },
methods: {
   scrollToProductList(){
       window.addEventListener('DOMContentLoaded', () => {
       // scroll animation
       document.getElementById('product-list-anchor').scrollIntoView(true);
     });
},

我的 URL 案例示例:

http://www.example.com/Product/list?search=&sort=3&type=-1&event%5B%5D=11&pagination=1

谢谢!!

标签: javascriptphphtmlvue.jsredirect

解决方案


我试图取消设置滚动行为,允许页面跳转到所需的部分,然后设置回平滑滚动行为。所以它现在可以在没有滚动行为的情况下工作。感谢所有的评论:)

我的代码:

scrollToProductList(){

  window.addEventListener('DOMContentLoaded', () => {

      // select the whole html & disable smooth-scroll behavior in css
      let htmlElement = document.querySelector('html');
      htmlElement.style.scrollBehavior = 'auto';

      // go to the anchor point
      document.getElementById('product-list-anchor').scrollIntoView(true);

      // enable smooth-scroll behavior again
      htmlElement.style.scrollBehavior = 'smooth';

  });

}


推荐阅读