使用javascript/jquery居中左对齐文本

center left aligned text using javascript/jquery

本文关键字:左对齐 文本 jquery javascript 使用      更新时间:2023-09-26

基本上,我要做的就是根据宽度将所有左对齐的文本居中,方法是获取每个文本的宽度,然后将左距设置为宽度的负一半,但现在它只适用于第一段。

我尝试使用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 />');    
   });
});