问题描述
我正在做一个滚动评论部分,它的工作原理是由几个元素回显由php有他们的顶部属性动画与javascript。一切似乎都工作正常,除非我将它们的位置设置为绝对和同时使用JavaScript,这导致text-align:center只有当文本中有多行时工作。这是我的代码:
HTML(大致像这样,通过PHP回声,也为内联样式道歉)
< div id =element0style =position:absolute; text-align:center;> Hello world!< / div>
< div id =element1style =position:absolute; text-align:center;> Hello world!< / div>
< div id =element2style =position:absolute; text-align:center;> Hello world!< / div>
< div id =element3style =position:absolute; text-align:center;> Hello world!< / div>
Javascript
var offset = 0;
var i = 0;
for(i = 0; i obj = document.getElementById(element+ i);
obj.style.top = offset +px;
offset + = obj.clientHeight;
}
function moveComments(){
var i1 = 0;
for(i1 = 0; i1< 3; i1 ++){
obj = document.getElementById(element+ i1);
obj.style.top = parseInt(obj.style.top) - 1 +'px';
if(parseInt(obj.style.top)< = -offset)
obj.style.top = offset + 100 +px;
}
}
setInterval(moveComments,10);
解决方案
position: code>使元素的宽度自动缩小以适合其内容。
text-align:center
在块元素的边界内居中文本。
如果块元素的宽度不大于文本宽度,则不会执行任何操作。
你需要给它一个更大的宽度。
I'm making a scrolling comment section, it works by having several elements echoed by php have their top property animated with javascript. Everything seems to be working fine except when I set their position to absolute and use javascript simultaneously, this results in text-align:center only working whenever there is more than one line in the text. Here is my code:
HTML (Roughly goes like this, is echoed through PHP, also apologies for the inline styling)
<div id="element0" style="position:absolute;text-align:center;">Hello world!</div> <div id="element1" style="position:absolute;text-align:center;">Hello world!</div> <div id="element2" style="position:absolute;text-align:center;">Hello world!</div> <div id="element3" style="position:absolute;text-align:center;">Hello world!</div>
Javascript
var offset = 0; var i = 0; for(i = 0; i < 3; i++) { obj = document.getElementById("element" + i); obj.style.top = offset + "px"; offset += obj.clientHeight; } function moveComments() { var i1 = 0; for(i1 = 0; i1 < 3; i1++) { obj = document.getElementById("element" + i1); obj.style.top = parseInt(obj.style.top) - 1 + 'px'; if(parseInt(obj.style.top) <= -offset) obj.style.top = offset + 100 + "px"; } } setInterval(moveComments, 10);
解决方案
position: absolute
causes the element's width to automatically shrink to fit its content.
text-align: center
centers text within the bounds of the block element.
If the block element is not wider than the text, it won't do anything.You need to give it a larger width.
这篇关于text-align:中心不工作时位置:绝对与javascript?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!