2013-05-10 69 views
0

正如標題所示,我正在做我的第一個響應式設計網站..我有一個圖像滑塊div設置使用像素和媒體查詢。我希望能夠訪問寬度,以便我可以告訴圖像滑塊我需要移動多遠。不幸的是,媒體查詢似乎沒有改變HTML。是否有任何解決方法來獲取該信息,以便我可以在JavaScript中使用它。css響應式設計具有dificulty訪問寬度與javascript

這裏是一個簡單的網頁例子玩和的jsfiddle http://jsfiddle.net/synthet1c/sNbW9/

感謝您的幫助

body{ 
    position:absolute; 
    background:red; 
    width:100%; 
    height:100%; 
} 

#outer{ 
    position:absolute; 
    width:80%; 
    height:80%; 
    background:red; 
    background-image:url('http://www.largepictures.net/largepictures/scenery/largepictures_scenery_large_3066.jpg'); 
    background-position: center; 
    margin:auto; 
} 

#inner{ 
    width:80%; 
    height:80%; 
    background:rgba(255,0,0,0.3) 
    margin:auto; 
    margin-top:5%; 
} 

<script> 

document.getElementById('inner').onclick = function(){ 
    alert(document.getElementById('inner').style.width); 
} 

</script> 

<div id="outer"> 

    <div id="inner">click the box to get width</div> 

</div> 

回答

1

element.style對象僅適用於與style屬性設置屬性(如名稱可能暗示)。要爲它的風格使用樣式表元素集檢索CSS設置:

document.getElementById('inner').onclick = function(){ 
    alert(window.getComputedStyle(document.getElementById('inner'), null).width); 
} 

JS Fiddle demo

參考文獻:

+0

非常感謝大衛,完美的作品! – synthet1c 2013-05-10 19:06:56

+0

非常歡迎,我很樂意幫助! =) – 2013-05-10 19:08:58

0

我犯了一個小片段爲我自己,因爲這是我一直需要有一段

var comStyle = function(element , pseudoElt){ 
    if(!pseudoElt){pseudoElt = null} 
    return window.getComputedStyle(document.getElementById(element), pseudoElt); } 

功能這有我的思想,但...難道我能夠改變的原型,所以如果元素.style.something equals和空字符串,然後使用getComputedStyle()從樣式表中獲取實際值?