2016-06-09 74 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哇哈哈,这是很多!但是谢谢你! –