2013-02-08 29 views
0

如何讓一個html元素改變,如果媒體寬度低於,比如說726px?響應動態html

例如我有一個圖像,如果介質寬度低於726像素,我想用另一個圖像進行更改。

回答

2

我建議您捆綁低分辨率樣式,你可以通過在你以下鏈接激活一個單獨的css文件HTML頭部分:

<link rel="stylesheet" media="only screen and (max-width:726px)" href="your-low-res-styles.css" title="norrowscreen" /> 

關於你的問題:「有沒有辦法改變的HTML ...」: 在你的代碼包含一個matchMedia聽衆:

if (window.matchMedia !== undefined) { 
    var mq = window.matchMedia("(max-width: 726px)"); 
    mq.addListener(onWidthChange); 
    onWidthChange(mq); 
} 
function onWidthChange(mq) { 
    if (mq.matches) { 
     $("#img0").attr("src", url1); 
    } else { 
     $("#img0").attr("src", url2); 
    ); 
}; 
2

設置CSS生效,直到726px

@media screen and (max-width: 726px) { 
    background-image: url(image-med.png); 
} 

@media screen and (min-width: 727px) { 
    background-image: url(image-big.png) 
} 
+0

這很好,但我想在html insted背景圖像的標記中使用圖像。有沒有辦法改變HTML代碼取決於媒體的寬度,就像在CSS? – user2013488

+0

你可以使用一個小的jquery插件:https://github.com/teleject/hisrc,然後將你的'img'標籤設置爲:'' – ashley

0
@media only screen and (max-width: 726px){ 
#div{ background-image: url(image-1.png)} 
} 
@media only screen and (min-width: 727px){ 
#div{ background-image: url(image-2.png)} 
} 
+0

這很好,但我想在html中使用標籤insted背景圖。有沒有辦法改變HTML代碼取決於媒體的寬度,就像在CSS? – user2013488