簡體   English   中英

如果瀏覽器窗口寬度小於,則隱藏元素並顯示其他

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

當用戶將其瀏覽器窗口調整為小於990px​​的寬度時,我想隱藏一個元素並顯示另一個元素。

  • 當窗口寬度小於990px時隱藏largeElement

  • 當窗口寬度小於990px時顯示smallElement


<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";
}

您可以使用CSS3媒體查詢來完成所有操作

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

    #smallElement {
        display: block;
    }
  }
</style>

我知道這並不是您要的,但這是IMO問題的最佳解決方案。

使用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;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM