使用javascript/jquery居中左对齐文本
center left aligned text using javascript/jquery
基本上,我要做的就是根据宽度将所有左对齐的文本居中,方法是获取每个文本的宽度,然后将左距设置为宽度的负一半,但现在它只适用于第一段。
我尝试使用inline-block
,使宽度是准确的文本,而不是父继承的宽度?我仍然希望块元素的行为像块元素。
当页面加载时,我怎么能让这个应用到所有的文本?
此外,我希望这对一个页面上的所有文本(p
, li
, pre
, blockquote
)都有效,是否有更好的方法来做到这一点?我想我可以列出函数中的所有内容。
<html>
<head>
<title>center left aligned text using javascript/jquery</title>
<style type="text/css" media="screen">
* {
margin: 0;
padding: 0;
}
#container {
margin: 200px auto;
width: 1280px;
height: 800px;
border: #000 1px solid;
}
#container p {
background: #eee;
display: inline-block;
left: 50%;
max-width: 500px;
position: relative;
}
</style>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
$(function() {
var width = $("p").width();
$('p').css('margin-left', -width / 2);
});
});
</script>
</head>
<body>
<div id="container">
<p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.</p>
<p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit.</p>
<p>Lorem ipsum dolor sit amet.</p>
</div>
</body>
</html>
编辑:如果我插入一个块元素后,它的行为正确
$("p").each(function () {
var width = $(this).width();
$(this).after('<br />');
$(this).css('margin-left', -width / 2);
});
您需要一个.each()
循环来查找宽度并分别为每个段落应用边距:
$("p").each(function () {
var width = $(this).width();
$(this).css('margin-left', -width / 2);
});
http://jsfiddle.net/mblase75/Cg45A/也就是说,只要你把inline-block
应用到段落中,我不认为它们看起来会像你想要的那样。你的最终设计应该是什么样子?
我认为这将是你能得到的最接近的,除非你添加更多的格式/元素的标记:
http://jsfiddle.net/sanpopo/rQG8c/$(document).ready(function () {
$('p').each(function() {
var width = $(this).width();
alert(width);
$(this).css({'margin-left': -width / 2, 'text-align': 'center'}).after('<br /><br />');
});
});
相关文章:
- D3动态垂直对齐文本
- 左对齐表单
- 如何仅在点击换行符时左对齐居中文本
- 计算圆心以在中间对齐文本
- JSSOR Slider-iOS中页面向左对齐
- 对齐文本插件引导程序html
- 等间距DIV+最后一行左对齐的流体宽度
- 将一个子对象左对齐,将第二个子对象右对齐extjs
- 100%高度输入字段,并垂直对齐文本
- CSS / Javascript微调器对齐文本中间
- 使用javascript/jquery居中左对齐文本
- 对齐文本与按钮在可折叠集jquery移动
- 垂直对齐文本与短长文本按钮
- 在javascript中右对齐文本
- Javascript动态创建span并垂直对齐文本:文本留在底部
- 使用Raphael's库绘制左对齐文本
- 围绕中心字对齐文本
- 在HTML 5画布的每一边对齐文本
- 使用向左拉/向右拉时引导程序未正确对齐文本
- 将文本向左对齐&圆的右侧取决于数据