【发布时间】:2017-07-16 06:06:52
【问题描述】:
如何使用 javascript 更改媒体查询中定义的元素?
我的目的是让隐藏的元素用 javascript 可见,而这个元素应该只在屏幕尺寸小于 1000 像素的情况下可见。因此,一旦元素在屏幕小于 1000 像素时可见(通过鼠标单击),当用户随后将窗口大小调整为大于 1000 像素时,该元素应该被隐藏。
这是代码,在代码本身中有一些用途的解释。
<!DOCTYPE html>
<html lang="en">
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<style media="screen" type="text/css">
#mobile-only, #mobile-only-after-click { display: none; }
@media screen and (max-width: 1000px) {
#mobile-only { display: block;}
}
</style>
<script>
function show () {
document.getElementById("mobile-only-after-click").style.display = "block";
}
</script>
</head>
<body>
<div>In desktop view this is the only visible div</div>
<div id="mobile-only">In mobile view this div is extra. <a href="#" onclick="show(); return false;">Click</a> to see a third div</div>
<div id="mobile-only-after-click">This third div should only be visible for mobile users. It should be hidden for desktop users after resizing the window to a larger size, after it was shown in a small screen upon a click.</div>
</body>
</html>
我尝试添加以下内容,但它不起作用。第三个 div 在显示后不会隐藏,并且在该事件之后使窗口宽度超过 1000 像素。
@media screen and (min-width: 1000px) {
#mobile-only-after-click { display: none; }
}
【问题讨论】:
-
当您使用 javascript 更改内联样式时会发生这种情况,它们会覆盖样式表。
-
感谢您的回复,但使用此解决方案,移动专用 div 始终处于隐藏状态,即使在应该可见的小屏幕上也是如此。
标签: javascript css media-queries