Soy nuevo en Javascript pero tengo el siguiente código tomado de W3 How to Scroll Back to Top Button: https://www.w3schools.com/howto/howto_js_scroll_to_top.asp
Me gustaría eliminar el botón en una consulta de medios de ancho mínimo (por ejemplo, ancho mínimo: 600 px), ¿es eso posible? Lo siento, estoy seguro de que esto es muy básico, gracias.
Código
var mybutton = document.getElementById("top-button"); // When the user scrolls down 20px from the top of the document, show the button window.onscroll = function() { scrollFunction() }; function scrollFunction() { if (document.body.scrollTop > 20 || document.documentElement.scrollTop > 20) { mybutton.style.display = "block"; } else { mybutton.style.display = "none"; } } // When the user clicks on the button, scroll to the top of the document function topFunction() { document.body.scrollTop = 0; document.documentElement.scrollTop = 0; } #top-button { display: none; position: fixed; bottom: 0.75rem; right: 0.75rem; z-index: 99; background-color: #1A936F; color: #f3e9d2; cursor: pointer; padding: 0.75rem; border-radius: 0.5rem; font-size: 1.1rem; } <button onclick="topFunction()" id="top-button" title="Go to top">Top</button>Utilice la propiedad window.innerWidth .
Algo como,
window.onscroll = function() { if (window.innerWidth <= 600) { scrollFunction(); } };var mybutton = document.getElementById("top-button"); var x = window.matchMedia("(max-width: 600px)"); // When the user scrolls down 20px from the top of the document, show the button window.onscroll = function() { scrollFunction() }; function scrollFunction() { if (x.matches) { mybutton.style.display = "none"; } else if (document.body.scrollTop > 20 || document.documentElement.scrollTop > 20){ mybutton.style.display = "block"; } else { mybutton.style.display = "none"; } } // When the user clicks on the button, scroll to the top of the document function topFunction() { document.body.scrollTop = 0; document.documentElement.scrollTop = 0; }¡Aquí, esto debería funcionar! Básicamente, puede usar window.matchMedia("(max-width: 600px)").matches para verificar el tamaño de la pantalla. Luego puede agregar el código js para que el botón no muestre ninguno.