2016-06-09 16 views
0

使用Yahoo Weather API。JS style.marginLeft&marginRight ='auto'not working

當試圖通過JS設置樣式邊距時,沒有任何反應。

這裏是我的腳本:

<script> 
var cBackFunction = function (data) { 
    console.log(data); 

    var location = data.query.results.channel.location; 
    var condition = data.query.results.channel.item.condition; 
    var wind = data.query.results.channel.wind; 
    var units = data.query.results.channel.units; 
    var link = data.query.results.channel.link; 
    var lastUpdated = data.query.results.channel.lastBuildDate; 
    var conditionCode = condition.code; 
    var conditionText = condition.text; 

    var img = document.createElement("IMG"); 
    img.src = "https://s.yimg.com/zz/combo?a/i/us/we/52/" + conditionCode + ".gif"; 
    img.style.marginLeft = "140px"; 

    document.getElementById('Weather-Description2').appendChild(img); 

    document.getElementById('Weather-Location2').innerHTML = location.city; 
    document.getElementById('Weather-Region2').innerHTML = location.region; 
    document.getElementById('Weather-Temp2').innerHTML = condition.temp; 
    document.getElementById('Weather-Unit2').innerHTML = units.temperature; 
    document.getElementById('Weather-WindSpeed2').innerHTML = wind.speed; 
    document.getElementById('Weather-Link2').href = link; 
    document.getElementById('lastUpdate2').innerHTML = lastUpdated; 
    document.getElementById('Weather-text2').innerHTML = "["+conditionText+"]"; 
    document.getElementById('Weather-text2').style.marginLeft = 'auto';  //not working 
    document.getElementById('Weather-text2').style.marginRight = 'auto';  // not working 
} 

HTML:

<strong id="Weather-text2"></strong> 

如果我改變auto「100px的」 特定像素那麼它的工作原理。可JS在邊緣使用auto?在marginLeftmarginRight上的auto的原因是自動居中該元素。如果是這樣,我該如何正確實施?

回答

3

A <strong>元素默認爲display: inline

自動邊距中心元素是display: block(雖然因爲您將缺省設置爲width: auto,除非您也減小寬度,否則這將不會產生實際效果)。

在最近的塊祖先元素上設置text-align: center以居中文本。

+0

啊,那工作。如果你不介意告訴我,你是怎麼知道某些html元素是內聯顯示的,而其他的則顯示爲block? –

+0

當時[它簡單得多](https://www.w3.org/TR/html4/),我閱讀了HTML規範,然後就是今天。 – Quentin

+0

ahh哇哈哈,這是很多!但是謝謝你! –