当语言改变时,如何在textarea中改变光标位置?

时间:2017-09-04 11:19:20

标签: javascript jquery html

我有textarea,可以使用英语和阿拉伯语。

英语从左到右开始。因此,光标应该从左侧开始。

阿拉伯语从右边开始。所以光标应该从右边开始。

当用户更改语言时,如何更改光标的位置?如果他的语言是英语,则光标应该在左侧,反之亦然。

用户可以使用键盘中的ALT + SHIFT更改其语言。

我试过这个,但它没有给我任何结果。

<textarea class="form-control description arabic" id="txt_desc" name="txt_desc" 
          placeholder="Description"></textarea>

.arabic{text-align:right;}

<script type="text/javascript">
    jQuery(document).ready(function($) {
        var reverseFunc = function() {
            $('textarea').each(function() {
                if($(this).hasClass('arabic')) {
                    // do the invert magic...
                    var val = $(this).val();
                    var newVal = val.charAt(val.length-1) + substr(0, val.length-1);
                    $(this).val(val);
                }
            });
        }

        $('textarea').bind('keyup', reverseFunc);
    });
</script>

使用shiftkey:

var x = document.getElementById("txt_desc");
    if (event.shiftKey) {
        document.getElementById('txt_desc').style.direction="rtl";
    }else{
         document.getElementById('txt_desc').style.direction="ltr";
    }

4 个答案:

答案 0 :(得分:2)

检查关键字上的第一个字符,如果它是阿拉伯语添加此direction: rtl;

var la_ar = 
["ي","و","ه","ش","س","ق","ف","غ","ع","ض","ص","ن","م","ل","ك","ظ","ط","ز","ر","ذ","د","خ","ح","ج","ث","ت","ب","ا"]

&#13;
&#13;
$("input").keyup(function(){
var la_ar = 
["ي","و","ه","ش","س","ق","ف","غ","ع","ض","ص","ن","م","ل","ك","ظ","ط","ز","ر","ذ","د","خ","ح","ج","ث","ت","ب","ا"]
    var bla = $(this).val();
    var blaـl = bla.charAt(0);
    if($.inArray(blaـl, la_ar) > -1 ){
      //alert('in');
      $(this).css("direction","rtl");


    }else{
      //alert('out');
      $(this).css("direction","ltr");
    }
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text">
&#13;
&#13;
&#13;

答案 1 :(得分:0)

 use the css attribute direction

    direction: rtl;

    In Javascript your code add this

    var x = document.getElementById("txt_desc");
        if (event.shiftKey) {
            document.getElementById('txt_desc').style.direction="rtl";
        }else{
             document.getElementById('txt_desc').style.direction="ltr";
        }

答案 2 :(得分:0)

你必须使用Html5属性才行。

.arabic{ direction: rtl;}

答案 3 :(得分:0)

你可以试试这个:

<textarea style="direction: rtl"></textarea>