As shown in figure:
1. Locate the location of the element to be located. For example, on the Y-axis, use offsetTop to locate the distance from the top of the parent element. 2. Use the scrollTop property to scroll its parent element to the appropriate location.
<! DOCTYPE html> <html> <head> <meta charset="utf-8"> <script> function dw(){ let [parentDoc,childDoc]= [document.querySelector('#fjd'),document.querySelector('.zjd')]; parentDoc.scrollTop = childDoc.offsetTop - parentDoc.offsetHeight /2 ; / / if than div high make its center childDoc style.css. Background = 'red'} < / script > < / head > < body > < button onclick = "dw ()" > locate < button > < div id="fjd" style="height:100px; overflow:auto; width: 200px;" > <div > found </div> <div > found </div> <div > found </div> <div > found </div> <div > found </div> <div > found </div> < ZJD > found </div> <div> Found </div> <div> Found </div> Found </div> <div> Found </div> </div> found </div> found </div> Found </div> Found </div> </div> </body> </html>Copy the code
To your help point attention, not regularly update JS interesting little knowledge.