繁体   English   中英

CSS Media JS不适用于媒体样式

[英]css media JS does not work for media style

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
.mobile {display:none;}
.desktop {display:block;}

@media screen and (max-width : 320px) {
    .mobile {display:block;}
    .desktop {display:none;}
</style>
</head>
<body>
<div class="desktop">
    <button onclick="myFunction()">calculate</button>
    <p id=result></p>
</div>
<div class="mobile">
    <button onclick="myFunction()">calculate</button>
    <p id=result></p>
</div>
<script>
    function myFunction() {
        var x = 2;
        var y = x + 3;
        document.getElementById("result").innerHTML = y;
     }
</script>
</body>
</html>

JS仅适用于屏幕宽度大于320像素的桌面。 当浏览器的窗口大小调整为320像素以下时,该功能不起作用。 为什么?

您仅使用getElementById()输出它。 此函数将仅获取DOM的第一个元素并对其进行更新。 如果小于320,则该元素被隐藏,您的输入也将被隐藏。

现在,我已经对其进行了更新,因此两个<p>元素都具有不同的ID,并在myFunction()事件处理程序中对其进行了更新。 这样,当您发出click事件时,两者都将更新。

 function myFunction() { var x = 2; var y = x + 3; document.getElementById("result1").innerHTML = y; document.getElementById("result2").innerHTML = y; } 
  .mobile { display: none; } .desktop { display: block; } @media screen and (max-width: 320px) { .mobile { display: block; } .desktop { display: none; } 
 <div class="desktop"> <button onclick="myFunction()">calculate</button> <p id=result1></p> </div> <div class="mobile"> <button onclick="myFunction()">calculate</button> <p id=result2></p> 

我不会推荐这种方法,但是您仍然可以使用此方法。 event.target.nextElementSibling ,这将始终获取触发点击的元素的下一个元素。 在你的情况下就足够了

 function myFunction() { var x = 2; var y = x + 3; event.target.nextElementSibling.innerText = y; } 
 .mobile { display: none; } .desktop { display: block; } @media screen and (max-width: 320px) { .mobile { display: block; } .desktop { display: none; } 
 <div class="desktop"> <button onclick="myFunction()">calculate</button> <p></p> </div> <div class="mobile"> <button onclick="myFunction()">calculate</button> <p></p> 

这是一个可扩展的解决方案。

最好用类名(结果)替换ID,并使用querySelectorAll获得具有该类名的所有节点。 然后遍历列表并设置innerHTML。

 <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <style> .mobile {display:none;} .desktop {display:block;} @media screen and (max-width : 320px) { .mobile {display:block;} .desktop {display:none;} </style> </head> <body> <div class="desktop"> <button onclick="myFunction()">calculate</button> <p class=result></p> </div> <div class="mobile"> <button onclick="myFunction()">calculate</button> <p class=result></p> </div> <script> function myFunction() { var x = 2; var y = x + 3; document.querySelectorAll(".result").forEach(function(element){ element.innerHTML = y }); } </script> </body> </html> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM