简体   繁体   中英

ScrollTop and ScrollTo Not working when changing innerHtml in a Div

I've read a bunch of topics on this and can't get any of the solutions I've seen to work. I have a Div "Section" where the contents (images, ext,etc) change by changing the innerhtml of a p. I can't figure out why I can't get it to scroll back to the top of #section when I switch between the 'panes' I've created by switching the innerhtml. In other words you load a pane by clicking on an image/text, you scroll down and see contents, then when you click into another 'pane' I just want it to scroll to the top. Any ideas?

This is what I currently have-

     case 1:

                    text = '[new html] ';

                    document.getElementById("demo").innerHTML = text;
                    document.getElementById("section").scrollTo(0,0);
                    break;

This is the HTML in my original body when it loads-

<div id="section"><div id="sectionwrap">

<p id="demo"></p>
</div></div>

Is this what you wanted? It's a little difficult to understand your question so bear with me :)

 window.onload = function(){ var x; document.getElementById('aa').onclick = function() { document.getElementById("section").scrollTop = 0; document.getElementById("section").style.background = 'red'; }; }; 
 p { padding: 0; margin: 0; font-family: Impact; line-height: 30px; } #sectionwrap { width: 100%; height: 1600px; background: rgba(255, 255, 122, .5); } #sidebar { width: 12.5%; height: 1000px; } #aa { background: blue; } #aa:hover { background: green; } #section { overflow-y: scroll; width: 100%; height: 200px; float: left; font-size: 2em; font-weight: bold; background: black; background-size: 100%; padding: 0%; text-align: center; } 
 <body> <div id="section"> <div id="sectionwrap"> <p id="demo">1 <br> <br> <br> <br> <div id="aa" onclick="z(9)">2</div> </p> </div> </div> </body> 

If anyone Else has this issue I got it to work.

I have a switch that changed between sets of innerHTML for the #section div (and toggles some other cosmetic things). If you have a similar setup within a page, Call your ScrollTop command before your switch. This achieved what I wanted which was to change the innerHTML by using a switch with different setups in each switch case, but have the div containing the new html to scroll back to the top when the "changing the contents" function was called.

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