首页 > 解决方案 > 如果窗口宽度小于给定值,我如何使用 JavaScript 在 Html 中隐藏文本,如果窗口宽度大于该值则显示它

问题描述

我尝试了window.screen.width方法,但似乎脚本只运行一次(当页面加载时),我正在寻找一种方法来使用,这样代码就可以一直运行
这是我的JavaScript代码:

var textinSelected = document.getElementById("selectedText").innerHTML;
setInterval(function(){
if (window.screen.width << 1200) {
    document.getElementById("selectedText").innerHTML = "";
  }
else if (window.screen.width >> 1200){
    document.getElementById("selectedText").innerHTML = textinSelected;
  }
});

这是目标 Html div:

 <div class="selected shadow-sm"><p id="selectedText">Catégories</p></div>

标签: javascripthtml

解决方案


使用 CSS,您更喜欢应该做的事情。

#selectedText {
  display: none;
}

@media screen and (min-width: 1200px) {

  #selectedText {
    display: block;
  }

}

或使用 JavaScriptwindow.matchMedia()

// Select the text element and value.
const selectedTextElement = document.querySelector('#selectedText');
const textValue = selectedTextElement.textContent;

// Create a media query.
const mediaQuery = window.matchMedia('(min-width: 1200px)');

// Toggle the text based on the media query.
const onMediaQueryChange = event => {
  if (event.matches) {
    selectedTextElement.textContent = textValue;
  } else {
    selectedTextElement.textContent = '';
  }
};

// Listen for changes whenever the screen size changes.
mediaQuery.addEventListener('change', onMediaQueryChange);

推荐阅读