隐藏元素并在浏览器窗口宽度小于时显示其他

Hide element and show other if browser window width is less than

本文关键字:小于 显示 其他 窗口 元素 浏览器 隐藏      更新时间:2023-09-26

我想隐藏一个元素,并在用户将其浏览器窗口的大小调整为小于 990px 的宽度大小时显示另一个元素。

  • 窗口宽度小于 990px 时隐藏大元素

  • 当窗口宽度小于 990px 时显示小元素


<div id="largeElement" style="width:900px;height:100px;background-color:#cc9966"></div>
<div id="smallElement" style="display:none;width:300px;height:100px;background-color:#39c"></div>


有谁知道一个javascript(没有jQuery)可以做到这一点吗?


这是一个简单的Javascript解决方案:

<div id="largeElement" style="width:900px;height:100px;background-color:#cc9966"></div>
<div id="smallElement" style="display:none;width:300px;height:100px;background-color:#39c"></div>
<script type="text/javascript">
toggle();
window.onresize = function() {
    toggle();
}
function toggle() {
    if (window.innerWidth < 900) {
        document.getElementById('largeElement').style.display = 'none';
        document.getElementById('smallElement').style.display = 'block';        
    }
    else {
        document.getElementById('largeElement').style.display = 'block';
        document.getElementById('smallElement').style.display = 'none';                
    }    
}
</script>

请参阅工作示例:http://jsfiddle.net/4p3nhy8b/

希望有帮助。

试试这个:使用 CSS:

@media (max-width : 990px){
   #largeElement{
       display : none;
   }
   #smallElement{
       display : block;
   }
}
@media (min-width : 991px){
   #largeElement{
       display : block;
   }
   #smallElement{
      display : none;
   }
}

使用 Javascript :

if(window.innerWidth < 990){
    document.getElementById("largeElement").style.display = "none";
    document.getElementById("smallElement").style.display = "block";
}
else{
    document.getElementById("largeElement").style.display = "block";
    document.getElementById("smallElement").style.display = "none";
}

使用 javascript :

function fun(){
   var width = screen.width;
   if( width < 990 ){
     document.getElementById("largeElement").style.display = "none";
     document.getElementById("smallElement").style.display = "show";
  }
}

load in body  <body onresize="fun()">

window.onresize = fun;

您可以使用 CSS3 媒体查询来完成所有这些

操作
<style>
    @media (max-width: 990px) {
    #largeElement {
        display: none;
    }
    #smallElement {
        display: block;
    }
  }
</style>

我知道这不是你所要求的,但这是IMO问题的最佳解决方案。