Home > Web Front-end > JS Tutorial > body text

How to Prevent Body Scrolling When Using a Modal in Bootstrap?

DDD
Release: 2024-10-19 18:07:01
Original
334 people have browsed it

How to Prevent Body Scrolling When Using a Modal in Bootstrap?

Preventing Body Scrolling During Modal Display

When using the Modal from Twitter's Bootstrap framework, you may encounter an issue where body scrolling continues when the modal dialog is open. This can be frustrating for users.

Solution

Bootstrap automatically adds a class, "modal-open," to the body when a modal is shown. You can utilize this feature by adding a CSS rule to your stylesheet:

<code class="css">body.modal-open {
    overflow: hidden;
}</code>
Copy after login

This will prevent body scrolling when the modal is open.

Bootstrap Version Considerations

Note that this solution has limitations based on your Bootstrap version.

  • Bootstrap 2.3.0 and Later: Twitter Bootstrap removed the "modal-open" class from the body in this version.

    • Workaround: You can add the class manually when the modal opens and remove it when it closes. This can be achieved using jQuery as follows:
    <code class="js">$("#myModal").on("show", function () {
        $("body").addClass("modal-open");
    }).on("hidden", function () {
        $("body").removeClass("modal-open")
    });</code>
    Copy after login
  • Bootstrap 3.0: The "modal-open" class is expected to return in version 3.0 explicitly for the purpose of preventing scroll.

IE Compatibility

Note that the solution is compatible with IE7 , as you have mentioned.

The above is the detailed content of How to Prevent Body Scrolling When Using a Modal in Bootstrap?. For more information, please follow other related articles on the PHP Chinese website!

source:php
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!