javascript - 如果窗口宽度小于给定值,我如何使用 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>
解决方案
使用 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);
推荐阅读
- java - 返回子列表中的第一项(如果有),如果为空则返回 null
- sql - 微软事务处理 SQL
- android - 如果要渲染的数据过多,双簧管会停止渲染音频
- python - 如何使用 html 或 python 将视频音乐上传到我的网站?
- path - 我想生成带有共享 limage 路径的链接
- cordova - Base64 to Gallery 插件在 Ionic 4 和 5 中不起作用
- javascript - 迁移到 webpack 5 时检测 webpack 构建中节点使用情况的静态分析
- r - 如何使数据框的行按一个或多个位置缩放?
- c - “*((char **)pTemp) = pTemp + 2;”是什么意思
- database - 以只读方式打开 MS Access 数据库而不锁定它