在大屏幕上隐藏 Javascript 按钮

Hidden Javascript Button on larger screen

我是 Javascript 的新手,但从 W3 如何滚动回到顶部按钮中获取了以下代码:https://www.w3schools.com/howto/howto_js_scroll_to_top.asp

我想删除最小宽度媒体查询(例如最小宽度:600 像素)上的按钮 - 这可能吗?抱歉,我确定这是非常基本的,谢谢。

代码

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>

使用window.innerWidth属性。

有点像,

window.onscroll = function() {
  if (window.innerWidth <= 600) {
    scrollFunction();
  }
};

样本:https://jsfiddle.net/codeandcloud/sezk0j74/

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;
}

给,这应该行得通! 基本上,您可以使用 window.matchMedia("(max-width: 600px)").matches 来检查屏幕尺寸。然后可以添加js代码让按钮显示none.