javascript - 使用javascript动态调整CSS

标签 javascript html css

我创建了一个带有博客的网页,用户可以在上面发帖。问题在于,随着越来越多的博客被发布,它们最终会超过页面的高度并进入后台。我发布博客的所有代码都在下面的内容类中:

.content {
float: left;
width: 664px;
text-align: justify;
margin: 0px 0px 30px 0;
padding: 10px 10px 10px 10px;
border-style: solid;
border-color: #D3D3D3;
border-width: 1px;
}

我想知道是否有一种方法可以使用 javascript 获取内容 Pane 的大小并将其分配给下面的页面类的高度:

.page {
background : url(images/page.png) repeat-y top;
height : 1000px;
padding : 0;
margin : 0;
}

我想我正在寻找的是一种使用 javascript 为页面重新分配 div 高度的方法

到目前为止的代码如下:

<?php
include 'connect.php';
include 'header.php';
?>

<form action = 'submitBlog.php' method = 'post'>
<input type="submit" name="Submit" value="Submit a blog"/>
</form>
<?php
$sql = mysql_query("select * from blog order by id desc");
while($row =  mysql_fetch_array($sql)){
$title = $row['title'];
$content = $row['content'];
$date = $row['date'];
$user = $row['user'];
?>

<table border = '1'>
<tr><td><font size = "5"><strong><?php echo $title; ?></strong></font></td><td> Posted on     <?php echo $date; echo "<br>by ".$user;?></td></tr>
<tr><td colspan = '2'><?php echo $content; ?> </td></tr>
<br>
</table>



<?php
}

include 'footer.php';
?> 

<script type = "text/javascript">
function setHeight() {
    var computedHeight = window.getComputedStyle(document.getElementById("content"),null).getPropertyValue("height") ; 
    document.getElementsByClassName('page')[0].style.height = computedHeight;
}
</script>

最佳答案

在纯Javascript中,你可以获得computed height这样的样式

var computedHeight = window.getComputedStyle(
                             document.getElementsByClassName("content")[0], null).                              
                             getPropertyValue("height");

这将返回 .content计算高度,单位为 px

现在将它设置为 page class like

document.getElementsByClassName('page')[0].style.height = computedHeight;

仅供引用:因为您只提到了 className 我使用了 >0 作为索引。但是,如果可能,最好对这些元素使用 id

关于javascript - 使用javascript动态调整CSS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20321947/

相关文章:

javascript - Codemirror 键盘映射 vim <Esc> 不工作

javascript - 根据选择创建动态选择表单

javascript - JQuery冲突导致文件上传失败

html - 图像没有作为列表的样式出现,为什么?

css - 悬停时忽略背景位置样式

javascript - 复制未转换的文本时替换文本中的字母

javascript - HTML5 setDragImage() : dragIcon. 宽度什么都不做

javascript - 按元素内容选择元素

javascript - session 在子域中可用但未实际显示

jquery - 为什么图像闪烁?