2014-09-12 67 views
1

我在我的頁面上使用媒體查詢,如果屏幕很小,我通過切換CSS顯示屬性顯示一些不同的html代碼。下載媒體查詢中的資產

爲小屏幕顯示我:

<div id="slot-machine-mobile" class="row show-for-small-only"> 
    <div class="small-12 small-centered columns"> 
     <img src="/assets/img/test-img.jpg"> 
    </div> 
</div> 

但據我瞭解,本次測試將毫克即使只是用大屏幕來下載。有沒有辦法讓圖像從不下載,如果他們正在使用大屏幕?

+0

你可以用'background-image'來做到這一點。 – loveNoHate 2014-09-12 10:26:16

+0

這將如何工作,只有在特定媒體查詢得到滿足時纔會下載? – panthro 2014-09-12 10:30:25

+0

@panthro嘗試我的代碼下面與jQuery,我用它在很多網站 – 2014-09-12 10:51:32

回答

2

您可以創建一個塊元素,並通過CSS爲其分配一個背景圖像。

<div class="img"> 

img { background-image:url("test-img.jpg"); } 

所以你的HTML coud看起來是這樣的:當你調整窗口大小的代碼

$(window).resize(function() { 
    if($(document).width()>width_large_screen) 
    { 
    $('#slot-machine-mobile img').attr('src','....'); 
    }else 
    { 
    $('#slot-machine-mobile img').attr('src','....'); 
    } 
}); 

使用:

<div id="slot-machine-mobile" class="row show-for-small-only"> 
    <div class="small-12 small-centered columns"> 
     <div class="img"></div> 
    </div> 
</div> 
+0

謝謝,但圖像沒有顯示。 – panthro 2014-09-12 10:36:05

+0

你應該將一個display:block應用於div.img的一些寬度和高度,我沒有指定它,因爲它不在問題範圍內 – Teo 2014-09-12 10:37:28

0

你可以使用jQuery在這種情況下,爲響應當文件準備就緒時:

$(document).ready(function() { 

     if($(document).width()>width_large_screen) 
    { 
     $('#slot-machine-mobile img').attr('src','....'); 
    }else 
    { 
    $('#slot-machine-mobile img').attr('src','....'); 
    } 
}); 

請嘗試並告訴我它是否可以,祝你好運