每个人。
我非常确定我的问题的答案相对简单。
我有一个包含以下代码的 .css 文件:
div.site
{
text-align:center;
border:2px solid #4b6c9e;
padding:1px;
margin-top:10px;
font-size:medium;
font-family:Verdana;
font-weight:bold;
height:25px;
}
然后,我有一个从 xml 构建我的 div
的 .js 文件。这是一个片段:
txt = txt + "<div class='site'><span class='link'><a class='nav' href=' " + siteUrl[0].firstChild.nodeValue + "' target='_blank'>" + siteName[0].firstChild.nodeValue + "</a></span></div>"
document.getElementById('portalLinks').innerHTML = txt;
我的 .html 文件包含以下内容:
<div id="portalLinks"></div>
我在页面上显示数据没有问题。我遇到的麻烦是
从我的 .css 文件中获取 site
类的高度。我正在使用以下代码:
var height = $(".site").height();
我想做的是使用这个height
,动态计算portalLinks
的高度:
$("#portalLinks").css({ "height": newHeight }) - where newHeight will be calculated based on `height`
提前致谢。
最佳答案
请记住,从 $(".site").height();
返回的值不是完整的 CSS 高度值。这只是一个数字。
使用第一次调用的结果调用 $("#portalLinks").css({"height": newHeight})
将设置一个无效值 25。您需要附加变量的单位——在本例中为 px
:
$("#portalLinks").css({"height":newHeight+'px'});
此外,值得一提的是,仅此调用就会将 #portalLinks
的高度设置为 one .site
元素的高度。
如果您想将高度设置为总高度,您需要以某种方式遍历 $('.site')
的结果:
var newHeight = 0;
$(".site").each(function(){
newHeight += $(this).height()
});
$("#portalLinks").css({"height":newHeight+'px'});
有关工作示例,请参阅此 fiddle :http://jsfiddle.net/EZWX4/
其他注意事项: .height()
返回 CSS height
属性的值。它不考虑填充和/或边框。
这在某些情况下可能会导致一些显示问题,因此您应该考虑改用 outerHeight()
。
此外:使用 outerHeight(true)
将在结果中包含定义的边距。
关于javascript - 从 css 文件中检索高度属性时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22310624/