vue realizes fast positioning of elements

Posted Jun 16, 20202 min read

Demand:There may be more than N data in a list. I select an item to view the details. If you scroll up and down to find this position again, it may be very troublesome. You need to scroll and scroll again. Therefore, a floating up and down arrow is needed to quickly locate to the previous position. The following is the effect I made~

Implementation ideas:

  1. The scroll bar scroll event must be heard first

    //If @click is not heard here, you can try @click.native

    {{item}}

    //What to display on each line

  1. When you click on this line, the distance between this item and the top of the parent element is obtained(because I have more data and a tree, so I used to get the index of this element and then multiply the height of the line by 30px, you can also get Its distance from the top

    clickItem({index}) {//index indicates the index of this row of data

     this.itemTop = index * 30; //Here 30 means that the height of my line is 30, the index of this line * 30 is the height from the vertex of the parent element

    }

  1. When scrolling, determine whether it is in the visible area, and determine whether it is blocked above or below

    scrollFun() {//This function is triggered when the scroll is detected

     this.isHoverIcon = false; //First hide the suspended image
     let scrollTop = document.querySelector('.parentBox').scrollTop; //The height of the scroll bar
     if(this.checkedItem &&(scrollTop> this.itemTop + 30 || scrollTop <this.itemTop-460) {//460 means the height of my parent box is 460, 30 means that the height of each row is 30
         this.isHoverIcon = true;
         if(scrollTop> this.itemTop + 30) {
             this.hoverIcon ='shangjiantou';
         } else if(scrollTop <this.itemTop-460) {
             this.hoverIcon ='xiajiantou';
         }
     }

    }
    //this.isHoverIcon indicates whether to display the floating Icon
    //this.checkedItem indicates whether there is a selected row, if not, no icon will be displayed in any case

At this point, click on the icon to quickly locate it, and I will not write the icon suspension css here. If you have any questions, please trust me directly, hee hee