Javascript 使一个div的宽度为另一个div的一半
我想做的是使一篇博客文章的标题正好是博客描述宽度的一半,并将其自身与博客描述宽度的50%对齐 这是我在JS中尝试的:Javascript 使一个div的宽度为另一个div的一半,javascript,css,Javascript,Css,我想做的是使一篇博客文章的标题正好是博客描述宽度的一半,并将其自身与博客描述宽度的50%对齐 这是我在JS中尝试的: var post\u title\u width=document.getElementById(“post\u description”).offsetWidth var post\u title\u width=post\u description*0.5; document.getElementbyId(“post\u title”).style.width=post\u
var post\u title\u width=document.getElementById(“post\u description”).offsetWidth代码>
var post\u title\u width=post\u description*0.5;
document.getElementbyId(“post\u title”).style.width=post\u title\u width代码>
HTML:
这是一个测试标题,测试一些javascript……。
您好,这里是一个测试描述,只是为了测试一些我想做的代码
我不使用css,因为我想测试javascript并学习如何有效地使用它。试试这个():
HTML
JS
JS用于位于计数器中心的边距内块,请尝试使用以下()命令:
如果您真的想在javascript中实现这一点,您会遇到一些问题:
您正在尝试使用getElementbyId以类名为目标
你的变量名搞砸了
跨距不是块元素,因此设置宽度不适用,除非设置溢出并将显示更改为块或内联块
不使用css的具体原因是什么?您还应该提供一个html片段,显示它们是如何相关/嵌套的。尝试将其舍入并添加一个单位:document.getElementbyId(“post_title”)。style.width=(post_title_width | 0)+“px”代码>这真的是CSS的一项工作,你可以用javascript来做,但这会很痛苦。太棒了!现在,我如何将标题(#一半)与描述的50%宽度对齐,实际上是文本对齐:居中;,但是根据描述的宽度(#head)对齐它
<div class="post">
<span class="post_title">This is a test title, testing some javascript...........</span><br>
<span class="post_description">Hello this is a test description right here, just to test some code im trying to do</span>
</div>
<div id="head"><div id="half"></div></div>
#head {
width: 300px;
height: 100px;
background: purple;
}
#half {
height: 100%;
background: green;
}
document.getElementById("half").style.width = document.getElementById("head").offsetWidth / 2 + 'px';
document.getElementById("half").style.marginLeft = (document.getElementById("head").offsetWidth - document.getElementById("half").offsetWidth) / 2 + 'px';
var post_description = document.getElementsByClassName("post_description")[0],
post_description_width = post_description.offsetWidth,
post_title_width = ( post_description_width * 0.5 ) + "px";
document.getElementsByClassName("post_title")[0].style.width = post_title_width;