2014-12-04 101 views
0

隱藏元素並顯示其他如果用戶將瀏覽器窗口的大小調整爲小於990像素的寬度大小,我想隱藏一個元素並顯示其他元素。隱藏元素,如果瀏覽器窗口寬度小於

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

  • 顯示smallElement當窗口寬度小於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的無),可以做到這一點的?


回答

4

這裏有一個簡單的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/

希望幫助秒。

+0

最佳工作javascript解決方案,謝謝@Gal V – Macchiato 2014-12-04 12:37:07

0

您可以用CSS3 media queries

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

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

做這一切,我知道這不是正是你問什麼,但它是解決這一問題的最佳解決方案海事組織。

+0

感謝@DoctorMick :) – Macchiato 2014-12-04 12:34:05

0

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

感謝@Nishit maheta你的答案:)如果ii對你有用,則爲 – Macchiato 2014-12-04 12:33:12

+0

。請放棄投票並標記正確的答案。 – 2014-12-04 12:35:07

+0

是的,我知道,我已經給了我最多的選票和正確的答案標記。感謝您的輸入! :) – Macchiato 2014-12-04 12:52:30

1

試試這個: 使用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"; 
} 
+0

我喜歡你的css3解決方案@Progeeker,謝謝:D – Macchiato 2014-12-04 12:35:39

相關問題