搜索文本内容,出现滚动条后可实现滚动效果

搜索后,可实现向上向下,第一个,最后一个滚动

输入框中输入关键子,可在失去焦点后调用search() 方法,然后关键子就会被标记上class,

文本内容要定义两份,每次重新搜索不同内容要重新使用原本文本(旧的加过了class),页面内容超出出现滚动调后方可实现滚动功能

const search=(keyWords:any)=> {
            state.checkIndex = 0;
            let allNum = 0;
            let regExp = new RegExp(keyWords, "g");
            state.log = state.logL.replace(
                regExp,
                '<span class="result" style="background:yellow;color:red;">' +
                    keyWords +
                    "</span>"
            );
            scrollToLocation(state.checkIndex);
        }
       const next=()=> {
            state.checkIndex++;
            scrollToLocation(state.checkIndex);
        }
      const  previous=()=> {
            state.checkIndex--;
            scrollToLocation(state.checkIndex);
        }
        const first=()=>{
          scrollToLocation(0);
        }
 
        const last=()=>{
          let mainContainer:any = document.querySelectorAll(".result");
          scrollToLocation(mainContainer.length-1);
        }
        // 这里使用定时的原因是因为第一次跳转的时候 dom 还在渲染,不一定能获取到,所以需要利用定时器多次获取
     const scrollToLocation=(checkIndex:any)=> {
            setTimeout(() => {
  
                    let mainContainer:any = document.querySelectorAll(".result");
                    let search:any = document.querySelector("#search");
                 
                     if(checkIndex>=0){
                      mainContainer[checkIndex].scrollIntoView();
                        // window.scrollTo({
                        //     top:
                        //     mainContainer[state.checkIndex].scrollTop - search.clientHeight,
                        //     behavior: "smooth",
                        // });
                        console.log(mainContainer[checkIndex].offsetTop - search.clientHeight)
                    }
                }, 300);
        }
posted @ 2022-06-15 12:01  婷baby  阅读(196)  评论(0)    收藏  举报