Acordeón, preguntas frecuentes, spoiler y otros widgets desplegables

Acordeón y faq

Puede crear un acordeón, preguntas frecuentes, spoiler y similares utilizando Div y JavaScript.
Pero mejor: detalles y resumen

Es compatible con todos los navegadores modernos y este es un código semánticamente formateado correctamente, cuyo uso tendrá ventajas:

  1. ¡Las personas con discapacidad serán más fáciles de usar en su sitio! Su software (lectores de pantalla y similares) comprende perfectamente las etiquetas html5 y las procesará e informará correctamente a las personas sobre el contenido.
  2. La coherencia del texto mejorará y los motores de búsqueda podrán indexar mejor el sitio, ya que comprenderán mejor cómo se relacionan el texto visible y el oculto.
  3. Estará disponible para controlar elementos desde el teclado y otros dispositivos.
  4. Se reduce la cantidad de código javascript que se cargará, lo que aumenta la velocidad de carga de la página, la velocidad de procesamiento y la corrección.
  5. Mejora del rendimiento en Lighthouse, Google PageSpeed y otras herramientas similares.
  6. Funciona cuando javascript está desactivado.

Menos:

  1. Los navegadores más antiguos no conocen tales etiquetas y no ocultarán información.

HTML:

<details> <summary>- </summary> <p></p> </details> <details open> <summary>-  2</summary> <p>        </p> </details> <details> <summary>-  3</summary> <p></p> </details> 

Detalles / resumen de ejemplo simple

Demostración:


Por un lado, no se ve muy hermoso, por otro lado es neutral y puede caber fácilmente en muchos diseños. Por cierto, la vista predeterminada de la etiqueta Detalles es muy similar al spoiler del Habr, solo que necesita volver a pintarlo un poco, subrayarlo y obtener el semánticamente correcto, sin javascript y divs, el spoiler de Habrovsk.

Spoiler de Habr

Desafortunadamente, el marcador predeterminado tiene dos inconvenientes:

  1. Los navegadores antiguos no lo ven.
  2. Los navegadores de Webkit no permiten cambiar el símbolo del marcador.

Por esta razón, el marcador predeterminado debe estar oculto y crear uno propio.


Considere el primer ejemplo de Detalles / Resumen con un marcador de texto modificado:

Detalles / resumen con un marcador de texto modificado

CSS:

 summary::-webkit-details-marker{display:none;} summary::-moz-list-bullet{list-style-type:none;} summary::marker{display:none;} summary { display:inline-block; padding: .3em .5em .3em .4em; font-size:1.4em; cursor: pointer; } summary:before { content: "+"; margin-right: .3em; } details[open] > summary:before { content: "–"; } summary ~ * { padding:0 1em 0 1em; } summary:focus { outline:0; box-shadow: inset 0 0 1px rgba(0,0,0,0.3), inset 0 0 2px rgba(0,0,0,0.3); } details{ display:block; margin-bottom: .5rem; } 

Para los marcadores predeterminados, mostramos: none y mostramos alternativas con resumen: antes de {content: "+";}

resumen: foco - trazo usando recuadro-sombra, esto es necesario para el teclado para que el elemento activo sea visible y pueda moverse con la tecla de tabulación y abrir y cerrar con un espacio.

Para la etiqueta de resumen, configuré display: inline-block: esto es para que no se extienda al ancho completo y solo se pueda hacer clic en las palabras, y no en toda la línea.

Demostración:


Marcador de texto a la derecha + texto simple y animación de marcador:

Detalles / Resumen: marcador de texto a la derecha + animación simple de texto y marcador

CSS:

 summary::-webkit-details-marker{display:none;} summary::-moz-list-bullet{list-style-type:none;} summary::marker{display:none;} summary { display:inline-block; padding: .3em .5em .3em .4em; font-size:1.4em; cursor: pointer; } summary:after { content: "+"; margin-left: .3em; display: inline-block; transition: transform .5s; } details[open] > summary:after { transform: scale(1,-1); } summary ~ * { padding:0 1em 0 1em; } summary:focus { outline:0; box-shadow: inset 0 0 1px rgba(0,0,0,0.3), inset 0 0 2px rgba(0,0,0,0.3); } details[open] summary ~ *{ animation: sweep .5s ease-in-out; } @keyframes sweep { 0% {opacity: 0;} 100% {opacity: 1;} } details{ display:block; margin-bottom: .5rem; } 

En el nuevo ejemplo, utilizo resumen: después para el marcador en lugar de resumen: antes, para que aparezca a la derecha.

Animación de marcador usando transform: scale (1, -1);

Para todos los elementos que están después del resumen, configuré la animación para una apariencia suave usando animación: barrido .5s facilidad de entrada;

Demostración:


Marcador SVG + animación de rotación:

Detalles / Resumen - marcador svg + animación de rotación

CSS:

 summary::-webkit-details-marker{display:none;} summary::-moz-list-bullet{list-style-type:none;} summary::marker{display:none;} summary { display:inline-block; padding: .3em .6em .3em 1.5em; font-size:1.4em; cursor: pointer; position: relative; } summary:before { left: .3em; top: .4em; color: transparent; background: url("data:image/svg+xml;base64,PHN2ZyBoZWlnaHQ9IjM0IiB2aWV3Qm94PSIwIDAgMjQgMjQiIHdpZHRoPSIzNCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48cGF0aCBkPSJNOC41OSAxNi4zNGw0LjU4LTQuNTktNC41OC00LjU5TDEwIDUuNzVsNiA2LTYgNnoiLz48L3N2Zz4=") no-repeat 50% 50% / 1em 1em; width: 1em; height: 1em; content: ""; position: absolute; transition: transform .5s; } details[open] > summary:before { transform: rotateZ(90deg); } summary ~ * { padding:0 1em 0 1em; } details[open] summary ~ *{ animation: sweep .5s ease-in-out; } @keyframes sweep { 0% {opacity: 0;} 100% {opacity: 1;} } summary:focus { outline:0; box-shadow: inset 0 0 1px rgba(0,0,0,0.3), inset 0 0 2px rgba(0,0,0,0.3); } details{ display:block; margin-bottom: .5rem; } / svg + xml; base64, PHN2ZyBoZWlnaHQ9IjM0IiB2aWV3Qm94PSIwIDAgMjQgMjQiIHdpZHRoPSIzNCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48cGF0aCBkPSJNOC41OSAxNi4zNGw0LjU4LTQuNTktNC41OC00LjU5TDEwIDUuNzVsNiA2LTYgNnoiLz48L3N2Zz4 =") no-repeat summary::-webkit-details-marker{display:none;} summary::-moz-list-bullet{list-style-type:none;} summary::marker{display:none;} summary { display:inline-block; padding: .3em .6em .3em 1.5em; font-size:1.4em; cursor: pointer; position: relative; } summary:before { left: .3em; top: .4em; color: transparent; background: url("data:image/svg+xml;base64,PHN2ZyBoZWlnaHQ9IjM0IiB2aWV3Qm94PSIwIDAgMjQgMjQiIHdpZHRoPSIzNCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48cGF0aCBkPSJNOC41OSAxNi4zNGw0LjU4LTQuNTktNC41OC00LjU5TDEwIDUuNzVsNiA2LTYgNnoiLz48L3N2Zz4=") no-repeat 50% 50% / 1em 1em; width: 1em; height: 1em; content: ""; position: absolute; transition: transform .5s; } details[open] > summary:before { transform: rotateZ(90deg); } summary ~ * { padding:0 1em 0 1em; } details[open] summary ~ *{ animation: sweep .5s ease-in-out; } @keyframes sweep { 0% {opacity: 0;} 100% {opacity: 1;} } summary:focus { outline:0; box-shadow: inset 0 0 1px rgba(0,0,0,0.3), inset 0 0 2px rgba(0,0,0,0.3); } details{ display:block; margin-bottom: .5rem; } 

Resumen: antes tenía que ser seriamente rehecho:

  1. Posición de venta: absoluta; izquierda: .3em; arriba: .4em; ancho: 1em; altura: 1em;
  2. El marcador de texto debe establecerse en color: transparente; de lo contrario será visible.
  3. Colgamos la imagen usando el fondo.

También es necesario establecer la sangría izquierda del relleno en el resumen en 1.5em para que el texto y el icono no se superpongan entre sí.

Bueno, agregamos transform: rotateZ (90deg) para un hermoso giro de la flecha.

Demostración:


Si necesitamos el ícono svg a la derecha, entonces necesitamos cambiar el resumen: antes y poner a la derecha en lugar de a la izquierda.

Para resumen, ponga padding-right: 1.5em;

Detalles / Resumen - marcador svg a la derecha + animación de rotación

CSS:

 summary::-webkit-details-marker{display:none;} summary::-moz-list-bullet{list-style-type:none;} summary::marker{display:none;} summary { display:inline-block; padding: .3em 1.5em .3em .6em; font-size:1.4em; cursor: pointer; position: relative; } summary:before { right: .3em; top: .4em; color: transparent; background: url("data:image/svg+xml;base64,PHN2ZyBoZWlnaHQ9IjM0IiB2aWV3Qm94PSIwIDAgMjQgMjQiIHdpZHRoPSIzNCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48cGF0aCBkPSJNOC41OSAxNi4zNGw0LjU4LTQuNTktNC41OC00LjU5TDEwIDUuNzVsNiA2LTYgNnoiLz48L3N2Zz4=") no-repeat 50% 50% / 1em 1em; width: 1em; height: 1em; content: ""; position: absolute; transition: transform .5s; } details[open] > summary:before { transform: rotateZ(90deg); } summary ~ * { padding:0 1em 0 1em; } details[open] summary ~ *{ animation: sweep .5s ease-in-out; } @keyframes sweep { 0% {opacity: 0;} 100% {opacity: 1;} } summary:focus { outline:0; box-shadow: inset 0 0 1px rgba(0,0,0,0.3), inset 0 0 2px rgba(0,0,0,0.3); } details{ display:block; margin-bottom: .5rem; } / svg + xml; base64, PHN2ZyBoZWlnaHQ9IjM0IiB2aWV3Qm94PSIwIDAgMjQgMjQiIHdpZHRoPSIzNCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48cGF0aCBkPSJNOC41OSAxNi4zNGw0LjU4LTQuNTktNC41OC00LjU5TDEwIDUuNzVsNiA2LTYgNnoiLz48L3N2Zz4 =") no-repeat summary::-webkit-details-marker{display:none;} summary::-moz-list-bullet{list-style-type:none;} summary::marker{display:none;} summary { display:inline-block; padding: .3em 1.5em .3em .6em; font-size:1.4em; cursor: pointer; position: relative; } summary:before { right: .3em; top: .4em; color: transparent; background: url("data:image/svg+xml;base64,PHN2ZyBoZWlnaHQ9IjM0IiB2aWV3Qm94PSIwIDAgMjQgMjQiIHdpZHRoPSIzNCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48cGF0aCBkPSJNOC41OSAxNi4zNGw0LjU4LTQuNTktNC41OC00LjU5TDEwIDUuNzVsNiA2LTYgNnoiLz48L3N2Zz4=") no-repeat 50% 50% / 1em 1em; width: 1em; height: 1em; content: ""; position: absolute; transition: transform .5s; } details[open] > summary:before { transform: rotateZ(90deg); } summary ~ * { padding:0 1em 0 1em; } details[open] summary ~ *{ animation: sweep .5s ease-in-out; } @keyframes sweep { 0% {opacity: 0;} 100% {opacity: 1;} } summary:focus { outline:0; box-shadow: inset 0 0 1px rgba(0,0,0,0.3), inset 0 0 2px rgba(0,0,0,0.3); } details{ display:block; margin-bottom: .5rem; } 

Demostración:


Hagamos ahora uno de los ejemplos más comunes de crear un acordeón, donde habrá un ícono a la izquierda, fondo, sombras, efectos:

Acordeón - icono a la izquierda, fondo, sombras, efectos

CSS:

 body{background: #edf2f7;} details{ display:block; background: #fff; width:400px; box-shadow: 0 10px 15px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04); border-radius: 8px; overflow:hidden; margin-bottom: 1.5rem; } summary::-webkit-details-marker{display:none;} summary::-moz-list-bullet{list-style-type:none;} summary::marker{display:none;} summary { display:block; padding: .3em .3em .3em 1.4em; font-size:1.4em; cursor: pointer; position: relative; border-bottom: 1px solid #e2e8f0; } summary:before { top: .4em; left: .3em; color: transparent; background: url("data:image/svg+xml;base64,PHN2ZyBoZWlnaHQ9IjM0IiB2aWV3Qm94PSIwIDAgMjQgMjQiIHdpZHRoPSIzNCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48cGF0aCBkPSJNOC41OSAxNi4zNGw0LjU4LTQuNTktNC41OC00LjU5TDEwIDUuNzVsNiA2LTYgNnoiLz48L3N2Zz4=") no-repeat 50% 50% / 1em 1em; width: 1em; height: 1em; content: ""; position: absolute; transition: transform .5s; } details[open] > summary:before { transform: rotateZ(90deg); } summary ~ * { padding: 0 2em 10px 2em; } details[open] summary ~ *{ animation: sweep .5s ease-in-out; } @keyframes sweep { 0% {opacity: 0;} 100% {opacity: 1;} } summary:focus { outline:0; box-shadow: inset 0 0 1px rgba(0,0,0,0.3), inset 0 0 2px rgba(0,0,0,0.3); } / svg + xml; base64, PHN2ZyBoZWlnaHQ9IjM0IiB2aWV3Qm94PSIwIDAgMjQgMjQiIHdpZHRoPSIzNCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48cGF0aCBkPSJNOC41OSAxNi4zNGw0LjU4LTQuNTktNC41OC00LjU5TDEwIDUuNzVsNiA2LTYgNnoiLz48L3N2Zz4 =") no-repeat body{background: #edf2f7;} details{ display:block; background: #fff; width:400px; box-shadow: 0 10px 15px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04); border-radius: 8px; overflow:hidden; margin-bottom: 1.5rem; } summary::-webkit-details-marker{display:none;} summary::-moz-list-bullet{list-style-type:none;} summary::marker{display:none;} summary { display:block; padding: .3em .3em .3em 1.4em; font-size:1.4em; cursor: pointer; position: relative; border-bottom: 1px solid #e2e8f0; } summary:before { top: .4em; left: .3em; color: transparent; background: url("data:image/svg+xml;base64,PHN2ZyBoZWlnaHQ9IjM0IiB2aWV3Qm94PSIwIDAgMjQgMjQiIHdpZHRoPSIzNCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48cGF0aCBkPSJNOC41OSAxNi4zNGw0LjU4LTQuNTktNC41OC00LjU5TDEwIDUuNzVsNiA2LTYgNnoiLz48L3N2Zz4=") no-repeat 50% 50% / 1em 1em; width: 1em; height: 1em; content: ""; position: absolute; transition: transform .5s; } details[open] > summary:before { transform: rotateZ(90deg); } summary ~ * { padding: 0 2em 10px 2em; } details[open] summary ~ *{ animation: sweep .5s ease-in-out; } @keyframes sweep { 0% {opacity: 0;} 100% {opacity: 1;} } summary:focus { outline:0; box-shadow: inset 0 0 1px rgba(0,0,0,0.3), inset 0 0 2px rgba(0,0,0,0.3); } 

Demostración:


Marcador de SVG en el efecto de flecha de rotación derecha + espejo:

Acordeón - icono a la derecha + efecto de rotación del espejo de la flecha

CSS:

 body{background: #edf2f7;} details{ display:block; background: #fff; width:400px; box-shadow: 0 10px 15px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04); border-radius: 8px; overflow:hidden; margin-bottom: 1.5rem; } summary::-webkit-details-marker{display:none;} summary::-moz-list-bullet{list-style-type:none;} summary::marker{display:none;} summary { display:block; padding: .3em 1em .3em .9em; border-bottom: 1px solid #e2e8f0; font-size:1.4em; cursor: pointer; position: relative; } summary:before { top: .4em; right: .3em; color: transparent; background: url("data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIyNCIgaGVpZ2h0PSIyNCIgdmlld0JveD0iMCAwIDI0IDI0Ij48cGF0aCBkPSJNMTYuNTkgOC41OUwxMiAxMy4xNyA3LjQxIDguNTkgNiAxMGw2IDYgNi02eiIvPjxwYXRoIGQ9Ik0wIDBoMjR2MjRIMHoiIGZpbGw9Im5vbmUiLz48L3N2Zz4=") no-repeat 50% 50% / 1em 1em; width: 1em; height: 1em; content: ""; position: absolute; transition: transform .5s; } details[open] > summary:before { transform: scale(1,-1); } summary ~ * { padding: 0 1em 10px 1.4em; } details[open] summary ~ *{ animation: sweep .5s ease-in-out; } @keyframes sweep { 0% {opacity: 0;} 100% {opacity: 1;} } summary:focus { outline:0; box-shadow: inset 0 0 1px rgba(0,0,0,0.3), inset 0 0 2px rgba(0,0,0,0.3); } / svg + xml; base64, PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIyNCIgaGVpZ2h0PSIyNCIgdmlld0JveD0iMCAwIDI0IDI0Ij48cGF0aCBkPSJNMTYuNTkgOC41OUwxMiAxMy4xNyA3LjQxIDguNTkgNiAxMGw2IDYgNi02eiIvPjxwYXRoIGQ9Ik0wIDBoMjR2MjRIMHoiIGZpbGw9Im5vbmUiLz48L3N2Zz4 =") no-repeat body{background: #edf2f7;} details{ display:block; background: #fff; width:400px; box-shadow: 0 10px 15px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04); border-radius: 8px; overflow:hidden; margin-bottom: 1.5rem; } summary::-webkit-details-marker{display:none;} summary::-moz-list-bullet{list-style-type:none;} summary::marker{display:none;} summary { display:block; padding: .3em 1em .3em .9em; border-bottom: 1px solid #e2e8f0; font-size:1.4em; cursor: pointer; position: relative; } summary:before { top: .4em; right: .3em; color: transparent; background: url("data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIyNCIgaGVpZ2h0PSIyNCIgdmlld0JveD0iMCAwIDI0IDI0Ij48cGF0aCBkPSJNMTYuNTkgOC41OUwxMiAxMy4xNyA3LjQxIDguNTkgNiAxMGw2IDYgNi02eiIvPjxwYXRoIGQ9Ik0wIDBoMjR2MjRIMHoiIGZpbGw9Im5vbmUiLz48L3N2Zz4=") no-repeat 50% 50% / 1em 1em; width: 1em; height: 1em; content: ""; position: absolute; transition: transform .5s; } details[open] > summary:before { transform: scale(1,-1); } summary ~ * { padding: 0 1em 10px 1.4em; } details[open] summary ~ *{ animation: sweep .5s ease-in-out; } @keyframes sweep { 0% {opacity: 0;} 100% {opacity: 1;} } summary:focus { outline:0; box-shadow: inset 0 0 1px rgba(0,0,0,0.3), inset 0 0 2px rgba(0,0,0,0.3); } 

Demostración:


Ahora puedes crear hermosos acordeones, spoilers y preguntas frecuentes, sin JavaScript, en HTML5 y CSS puro.

Antes de quitar el contorno, piense 100 veces cómo puede reemplazarlo, para que una persona pueda ver el foco y pueda moverse desde el teclado u otros dispositivos.

Si necesita para que cuando abra un spoiler, los otros se cierren, tendrá que usar javascript, a continuación le doy un ejemplo de código JS simple que resolverá este problema.

JavaScript:

 var details = document.querySelectorAll("details"); for(i=0;i<details.length;i++) { details[i].addEventListener("toggle", accordion); } function accordion(event) { if (!event.target.open) return; var details = event.target.parentNode.children; for(i=0;i<details.length;i++) { if (details[i].tagName != "DETAILS" || !details[i].hasAttribute('open') || event.target == details[i]) { continue; } details[i].removeAttribute("open"); } } 

Demostración:


Detalles de la tabla de soporte por navegadores.

Atentamente, Creador del Diseñador de aterrizaje para Freelancers CMS cPortfolio

Source: https://habr.com/ru/post/465623/


All Articles