Bootstrap 3 modal dispara y hace que la página se desplace a la izquierda momentáneamente / problemas de la barra de desplazamiento del navegador


Estoy trabajando en un sitio usando Bootstrap 3.1.0.

Notarás que cuando se abre la ventana modal, la barra de desplazamiento del navegador desaparece por una fracción de segundo y luego vuelve. Hace lo mismo cuando lo cierras.

¿Cómo puedo hacer que se abra y cierre sin interacción con la barra de desplazamiento del navegador? He visto publicaciones en stack donde las personas tenían problemas, pero no puedo encontrar una respuesta específica a mi problema, por lo que si alguien más ha hecho esta solicitud y alguien lo sabe sobre eso y quiere vincularme a él, lo agradecería. He buscado por cerca de 2 horas para esto antes de publicar.

Author: lowtechsun, 2013-11-13

20 answers

Esto es lo que encontré en github cuando busco sobre este problema y para mí funciona bien

Js:

    $(document).ready(function () {
    $('.modal').on('show.bs.modal', function () {
        if ($(document).height() > $(window).height()) {
            // no-scroll
            $('body').addClass("modal-open-noscroll");
        }
        else {
            $('body').removeClass("modal-open-noscroll");
        }
    });
    $('.modal').on('hide.bs.modal', function () {
        $('body').removeClass("modal-open-noscroll");
    });
})

Css use este css si tiene nav-fixed-top y navbar-fixed-bottom :

body.modal-open-noscroll
{
    margin-right: 0!important;
    overflow: hidden;
}
.modal-open-noscroll .navbar-fixed-top, .modal-open .navbar-fixed-bottom
{
    margin-right: 0!important;
}

O utilice este css si tiene navbar-default

body.modal-open-noscroll 
{
  margin-right: 0!important;
  overflow: hidden;
}
.modal-open-noscroll .navbar-default, .modal-open .navbar-default 
{
  margin-right: 0!important;
}
 19
Author: user4314713,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-09-04 13:06:16
.modal {
 overflow-y: auto;
}

.modal-open {
 overflow: auto;
}

Se deshará de él. Esto se agregó para que los modales funcionen de manera más responsable, para que pueda desplazarse hacia abajo y ver un modal si la pantalla es demasiado corta. También evita que el fondo sea desplazable mientras un modal está arriba. Si no necesitas esa funcionalidad, entonces puedes usar el css que publiqué.

Algo más de información: Están configurando .modal-abierto en el cuerpo, lo que evita todo desplazamiento en el cuerpo y oculta la barra de desplazamiento del cuerpo. Entonces, cuando el modal aparece tiene la oscuridad fondo que ocupa toda la pantalla, y que tiene overflow-y: scroll que obliga a la barra de desplazamiento a volver, por lo que si el modal extendido pasó la parte inferior de la pantalla todavía puede desplazarse por el fondo oscuro y ver el resto de la misma.

 87
Author: cjd82187,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-11-13 19:42:22

Arreglar el problema de desplazamiento a la izquierda se hace fácilmente usando CSS solo.

.modal-open[style] {
padding-right: 0px !important;
}

Simplemente estás sobrescribiendo un estilo en línea que existe en el código. Estoy usando el mío en una compilación de WordPress y el estilo en línea se estaba aplicando al cuerpo. Se veía así:

<body class="home blog logged-in modal-open" style="padding-right: 15px;">

Espero que esto ayude a alguien!

 61
Author: ben.kaminski,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-09-20 19:27:01
.modal {
    overflow-y: auto;
}

.modal-open {
    overflow: auto;
}

.modal-open[style] {
    padding-right: 0px !important;
}

Gracias a ben y cjd.

El código anterior parece funcionar para mí.

 30
Author: Tony S,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-08-16 12:15:34

Este es un problema reportado a bootstrap: https://github.com/twbs/bootstrap/issues/9855

Y esta es mi solución rápida temporal y también funciona usando la barra de navegación superior fija, solo usando javascript. Cargue este script junto con su página.

$(document.body)
.on('show.bs.modal', function () {
    if (this.clientHeight <= window.innerHeight) {
        return;
    }
    // Get scrollbar width
    var scrollbarWidth = getScrollBarWidth()
    if (scrollbarWidth) {
        $(document.body).css('padding-right', scrollbarWidth);
        $('.navbar-fixed-top').css('padding-right', scrollbarWidth);    
    }
})
.on('hidden.bs.modal', function () {
    $(document.body).css('padding-right', 0);
    $('.navbar-fixed-top').css('padding-right', 0);
});

function getScrollBarWidth () {
    var inner = document.createElement('p');
    inner.style.width = "100%";
    inner.style.height = "200px";

    var outer = document.createElement('div');
    outer.style.position = "absolute";
    outer.style.top = "0px";
    outer.style.left = "0px";
    outer.style.visibility = "hidden";
    outer.style.width = "200px";
    outer.style.height = "150px";
    outer.style.overflow = "hidden";
    outer.appendChild (inner);

    document.body.appendChild (outer);
    var w1 = inner.offsetWidth;
    outer.style.overflow = 'scroll';
    var w2 = inner.offsetWidth;
    if (w1 == w2) w2 = outer.clientWidth;

    document.body.removeChild (outer);

    return (w1 - w2);
};

Aquí está el ejemplo de trabajo: http://jsbin.com/oHiPIJi/64

 8
Author: Agni Pradharma,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-03-08 13:48:49

Si tienes la barra de navegación fija y no quieres desplazar el cuerpo hacia arriba cuando se abre modal, usa este estilo

.modal-open {
    overflow: visible;
}
.modal-open, .modal-open .navbar-fixed-top, .modal-open .navbar-fixed-bottom {
    padding-right:0px!important;
}
 7
Author: Calvin Grain,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-04-24 12:49:36

Ninguno de los elementos de esta página funcionó para mí en las versiones 3.3.4 y 3.3.5 Agregar este CSS ha resuelto el problema para mí.

body {
padding-right:0px !important;
margin-right:0px !important;
}
 5
Author: Dizzle,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-07-22 12:11:25
$('body').on('show.bs.modal', function () {
    if ($("body").innerHeight() > $(window).height()) {
        $("body").css("margin-right", "17px");
    }
}); 

$('body').on('hidden.bs.modal', function (e) {
    $("body").css("margin-right", "0px");
});

Esta pequeña corrección simula la barra de desplazamiento cuando se muestra el modal, agregando un margen derecho al cuerpo.

 4
Author: hect0r90,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-05-05 04:16:30

En mi caso, la etiqueta body ya especifica overflow:hidden.

Cuando se abre el diálogo modal, también agrega padding-right:17px; al cuerpo.

Mi código aquí

.modal-open {
  overflow: hidden!important;
  padding-right:0!important
}
 2
Author: KayJ,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-03-25 07:06:00

Para resolver el problema que causa que la página se desplace hacia la derecha

html, body{
  padding: 0 !important;
}
 2
Author: Femi-oke Anthony,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-07-21 15:10:09

html, body{
    padding-right: 0px !important; 
    position: relative!important;
}

Pruebe este código realmente está funcionando

 2
Author: beast.nil,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-08-25 04:29:06

Esta solución funciona para mí!!!!

.modal {
 overflow-y: auto;
}

.modal-open {
 overflow: auto;
}


.modal-open[style] {
padding-right: 0px !important;
}
 2
Author: Jigar Bhatt,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-03-26 03:33:00

A partir de Bootstrap 3.3.2 el comportamiento parece ser que las barras de desplazamiento se eliminan cuando se muestra el diálogo y Bootstrap agrega algún relleno derecho al elemento body para compensar el espacio previamente ocupado por la barra de desplazamiento. Desafortunadamente, esto no impide el cambio de pantalla, al menos en las versiones modernas de Chrome, IE, Firefox o Safari. Ninguna de las correcciones aquí solucionan completamente este problema, pero la combinación de las respuestas de ben.kaminski y parte de la respuesta de cjd82187 resuelve el problema solo con CSS:

/* removes inline padding added by Boostrap that makes the screen shift left */
.modal-open[style] {
    padding-right: 0px !important;
}

/* keeps Bootstrap from removing the scrollbar if it's there */
.modal-open {
    overflow: auto;
}

Como mencionó Ben.kaminski, el código se agregó a Twitter Bootstrap para que pueda desplazarse para traer el modal a la vista si está más allá de la parte inferior de la pantalla. Para conservar esa funcionalidad, puede envolver la solución CSS en una consulta de medios para que solo se aplique a las vistas grandes, algo como esto:

@media (min-width: 992px) {         
    .modal-open[style] {
        padding-right: 0px !important;
    }

    .modal-open {
        overflow: auto;
    }   
}
 1
Author: clav,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-03-11 16:30:11

Cuando se abre el modal bootstrap .la clase modal-open se establece en body tag. En esta etiqueta se establece overflow:hidden. tenemos que cambiar esto. Añade el siguiente código en tu CSS.

<style>
body.modal-open {
    overflow: visible !important;
}
</style>

Referencia: - Cómo arreglar el fondo modal de Bootstrap desplácese hacia arriba

 1
Author: Sudhanshu sharma,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-09-30 12:34:02

Mi página necesitaba una versión modificada del código de Agni Pradharma para evitar que cambiara cuando se mostraba el modal. Tengo un encabezado de navegación fijo y algunas páginas con desplazamiento, algunas sin. Demostración aquí: http://jsbin.com/gekenakoki/1 /

Usé tanto el css:

.modal {
    overflow-y: auto;
}

.modal-open {
    overflow: auto;
} 

Y el guión:

$(document.body)
.on('show.bs.modal', function () {
    if (this.clientHeight <= window.innerHeight) {
        return;
    }
    // Get scrollbar width
    var scrollbarWidth = getScrollBarWidth();
    if (scrollbarWidth) {
        $(document.body).css('padding-left', scrollbarWidth); 
    }
})
.on('hidden.bs.modal', function () {
    $(document.body).css('padding-left', 0);
});

function getScrollBarWidth () {
    var inner = document.createElement('p');
    inner.style.width = "100%";
    inner.style.height = "200px";

    var outer = document.createElement('div');
    outer.style.position = "absolute";
    outer.style.top = "0px";
    outer.style.left = "0px";
    outer.style.visibility = "hidden";
    outer.style.width = "200px";
    outer.style.height = "150px";
    outer.style.overflow = "hidden";
    outer.appendChild (inner);

    document.body.appendChild (outer);
    var w1 = inner.offsetWidth;
    outer.style.overflow = 'scroll';
    var w2 = inner.offsetWidth;
    if (w1 == w2) w2 = outer.clientWidth;

    document.body.removeChild (outer);

    return (w1 - w2);
};
 0
Author: knighter,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-11-21 04:33:40

Si alguien está usando react-bootstrap la solución es un poco más compleja porque react-bootstrap aplica estilos en línea al elemento body para manipular los estilos overflow y padding. Esto significa que debe reemplazar esos estilos en línea con !important

body.modal-open {
  // enable below if you want to additionally allow scrolling with the modal displayed
  // overflow: auto !important;

  // prevent the additional padding from being applied
  padding: 0 !important;
}

NOTA: si no habilita el desplazamiento (es decir, hace que la barra de desplazamiento sea visible) descomentando el estilo overflow, entonces el contenido de su página aparecerá desplazado por el ancho de la barra de desplazamiento (si la barra de desplazamiento visible que es).

 0
Author: pjs,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-06-01 18:47:44

Mi solución de Jquery:

var nb = $('nav.navbar-fixed-top');
$('.modal')
    .on('show.bs.modal', function () {
        nb.width(nb.width());
    })
    .on('hidden.bs.modal', function () {
        nb.width(nb.width('auto'));
    });
 0
Author: Goloveichuk,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-10-14 15:58:03

Para la versión Bootstrap 3.2.0 estas líneas en el relleno de archivos css solucionan el error:

.modal-open .navbar-fixed-top,
.modal-open .navbar-fixed-bottom {
padding-right: 17px;
}

Solución encontrada aquí

 0
Author: captain theo,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-15 21:37:26

Implementado esta solución simple

.modal-open {

  padding-right: 0 !important;

}

html {

  overflow-y: scroll !important;

}
 0
Author: harshal lonare,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-02-21 15:12:28

La mejor solución para mí fue usar esta configuración. Funciona para web y móvil

.modal-open {
   overflow: hidden;
   position: absolute;
   width: 100%;
   height: 100%;
}
 0
Author: Bartando,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-09-08 18:55:05