简体   繁体   中英

HTML <dialog> tag modal scrolling to bottom on open

When using the dialog HTML tag and calling the .showModal() method, it seems that when the modal content is longer than the dialog display area, the dialog will scroll automatically to the bottom on every open. Is there a clean way to suppress this behavior, so that the dialog content will stay at the very top on open?

 document.getElementById("openDialog").addEventListener("click", () => document.getElementById("modal").showModal()); document.getElementById("closeDialog").addEventListener("click", () => document.getElementById("modal").close());
 <button id="openDialog">Open</button> <dialog id='modal'> <h1>Hello world 1</h1> <h1>Hello world 2</h1> <h1>Hello world 3</h1> <h1>Hello world 4</h1> <h1>Hello world 5</h1> <h1>Hello world 6</h1> <h1>Hello world 7</h1> <h1>Hello world 8</h1> <h1>Hello world 9</h1> <h1>Hello world 10</h1> <button id="closeDialog">Close</button> </dialog>

Thanks to the explanation by @Teemu in the question's comments, the reason for this behavior is due to the button element getting focused on load.

For my case, I am using the button as a dismiss button, thus replacing the button with an a tag without the href attribute would solve the problem.

 document.getElementById("openDialog").addEventListener("click", () => document.getElementById("modal").showModal()); document.getElementById("closeDialog").addEventListener("click", () => document.getElementById("modal").close());
 <button id="openDialog">Open</button> <dialog id='modal'> <h1>Hello world 1</h1> <h1>Hello world 2</h1> <h1>Hello world 3</h1> <h1>Hello world 4</h1> <h1>Hello world 5</h1> <h1>Hello world 6</h1> <h1>Hello world 7</h1> <h1>Hello world 8</h1> <h1>Hello world 9</h1> <h1>Hello world 10</h1> <a id="closeDialog">Close</button> </dialog>

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