Position the anchor point inside the vue page

The last article wrote about the anchor point positioning across pages. The anchor point page is called in mounted and positioned to the anchor point position. Mounted will only be executed when the page is newly opened, so click to locate the anchor point in the current page. It doesn't work. The solution is to monitor whether the URL changes in the watch in main.js. If the URL changes, execute the anchor location method.

effect:

Add in mian.js

import {goAnchor,GetQueryString} from '../static/js/common.js';

new Vue ({

  from: '#app',

  router,

  render: h => h(App),

  mounted:function(){//Solve the bug that jumping to a new page is not fixed at the top by default

    this.$router.afterEach((to, from, next) => {

        window.scrollTo(0, 0)

    })

  },

  methods:{

    goAnchor,

    GetQueryString,

  },

  watch:{

    '$route.query':function(newVal,oldVal){

      var maodian = newVal.maodian;

      if(maodian){

        this.goAnchor('#'+maodian);

      }

    }

  }

})

The content of common.js introduced in mian.js

//Jump to anchor

function goAnchor(selector) {

    console.info("selector1",selector)

    var anchor = this.$el.querySelector(selector);//Get elements

    console.info("anchor",anchor)

    if(anchor) {

        setTimeout(()=>{//The page cannot be scrolled when the page is not rendered, so set the delay

            //anchor.scrollIntoView(); //js built-in method, which can scroll the view position to the element position

            

            var targetOffset=$(selector).offset().top; 

            console.info("targetOffset",anchor,targetOffset)

            $('html,body').animate({

                scrollTop: targetOffset

            },

            1000);

        },500);

    } 

};

//Get parameters

function GetQueryString(name){

    //var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");

    var href = window.location.href;

    var r = getSearchString(name,href);

    if (r != null) return decodeURI(r);

    return null;

}

function getSearchString(key, Url) {

    var str = Url;

    str = str.substring(1, str.length);    

    if(str.indexOf("?")!=-1){

        var arr = str.split("?")[1].split("&");// Get it? After the parameter content, and separate the string with & to obtain an element array like name=xiaoli

        var obj = new Object();

        // Separate each array element with = and assign it to the obj object

        for (var i = 0; i < arr.length; i++) {

            var tmp_arr = arr[i].split("=");

            obj[decodeURIComponent(tmp_arr[0])] = decodeURIComponent(tmp_arr[1]);

        }

        return obj[key];

    }    

}

export {

    goAnchor,

    GetQueryString

}

Guess you like

Origin blog.csdn.net/u012011360/article/details/103165531