我要做的是让博客文章的标题恰好是博客描述宽度的一半,并将自己调整为博客描述宽度的50%。
这是我在JS中尝试过的:
var post_title_width = document.getElementById("post_desciption").offsetWidth;
var post_title_width = post_description * 0.5;
document.getElementbyId("post_title").style.width = post_title_width;
HTML:
<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>
我没有使用css,因为我想测试javascript并学习如何有效地使用它。
答案 0 :(得分:0)
试试这个(example):
HTML
<div id="head"><div id="half"></div></div>
CSS
#head {
width: 300px;
height: 100px;
background: purple;
}
#half {
height: 100%;
background: green;
}
JS
document.getElementById("half").style.width = document.getElementById("head").offsetWidth / 2 + 'px';
JS为其中心的边距内部块尝试使用此(example):
document.getElementById("half").style.marginLeft = (document.getElementById("head").offsetWidth - document.getElementById("half").offsetWidth) / 2 + 'px';
答案 1 :(得分:0)
如果您真的想在javascript中使用它,那么您会遇到一些问题:
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;