Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
428 views
in Technique[技术] by (71.8m points)

javascript - use text-align smartly (if english dir=ltr if arabic dir=rtl)

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

  • English posts with direction LTR / text-align: left) and
  • Arabic posts with direction RTL / text-align: right.

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

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 ?!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.

Demo: jsFiddle

Script

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...