简体   繁体   中英

Scroll down to specific div when the user clicks the button

I want the screen to scroll down to the div. This div has an ID of 'weather-data'

I have tried the following;

document.getElementById('weather-data').scrollIntoView();

I have also tried using anchor tags this did not seem to work

The button which the user will click:

<button id="submit" onclick="myFunction()">
                    Submit
                </button> 

The function that runs when the button is clicked:

function myFunction(){
    cityName();

    getData();

    clear();

    document.getElementById('weather-data').scrollIntoView();
}

This is the div I want the screen to scroll to:

<div id="weather-data">

</div>

use the anchor tag to link the the div

 body{ margin: 0; } div{ height: 100vh; border: 1px solid black; } 
 <html> <body> <div id='a'>a</div> <div id='b'>b</div> <div id='c'>c</div> <div id='d'>d</div> <div id='e'>e</div> <button><a href='#c'>go to c</a></button> </body> </html> 

I fixed the issue I had to write an if statement to check if there was any text in the h1 element.

if(weatherMain != null){

                document.getElementById('icon').scrollIntoView();
                document.getElementById('weather-main').scrollIntoView();

            }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM