巧妙地使用文本对齐(如果英语 dir=ltr 如果阿拉伯语 dir=rtl)

我有一个社区网站,我希望用户写

I have a community web site and I want that users write

  • 带有方向 LTR/text-align: left) 的英文帖子和
  • 带有方向 RTL/text-align: right 的阿拉伯语帖子.

例如Google+ 和 twitter 提供了这样的 POST 解决方案.

E.g. Google+ and twitter provides such an POST solution.

当我从 rtl 或 ltr 中的数据库 post load 读取它时,我想自动添加方向属性到 post !但我不知道怎么做?!

I want add automatically direction attribute to post when i read it from data base post load in rtl or ltr ! but i don't know how ?!

推荐答案

您需要创建一个函数,其中包含您知道的所有字母 RTL 并在加载时检查.要显示 RTL,您需要 CSS 属性、directiontext-alignunicode-bidi.

You'll need to create a function that has all the letters you know are RTL and check when loading. To display RTL you need the CSS attributes, direction, text-align, and unicode-bidi.

演示:

function checkRtl( character ) {
    var RTL = ['ا','ب','پ','ت','س','ج','چ','ح','خ','د','ذ','ر','ز','ژ','س','ش','ص','ض','ط','ظ','ع','غ','ف','ق','ک','گ','ل','م','ن','و','ه','ی'];
    return RTL.indexOf( character ) > -1;
};

var divs = document.getElementsByTagName( 'div' );

for ( var index = 0; index < divs.length; index++ ) {
    if( checkRtl( divs[index].textContent[0] ) ) {
        divs[index].className = 'rtl';
    } else {
        divs[index].className = 'ltr';
    };
};

CSS

.rtl {
    direction: rtl; 
    text-align: right;
    unicode-bidi: bidi-override;
}

.ltr {
    direction: ltr; 
    text-align: left;
    unicode-bidi: bidi-override;
}

HTML

<div>hello</div>
<div>ظ</div>

相关文章