IE9中的文本对齐问题

Text Alignment Issue in IE9

本文关键字:对齐 问题 文本 IE9      更新时间:2024-03-10

我有一个输入字段,其中有一些文本。单击按钮后,我想将文本更改为居中、左对齐和右对齐。

它适用于所有浏览器,但不适用于IE9。

<!DOCTYPE html>
<html>
    <head>
        <title> Test for Text Align</title>
        <meta charset = "UTF-8" />
        <style type="text/css">
        #testBox{
            text-align: left;
        }
        </style>
    </head>
    <div>
        <input type="text" id ="testBox" name="testBox" value="testBox" maxlength="32" />
    </div>
    <div>
        <input type="button" onClick="testFunction('centeralign')" name="centeralign" id="centeralign" value="centeralign"/>
        <input type="button" onClick="testFunction('leftalign')" name="leftalign" id="leftalign" value="leftalign"/>
        <input type="button" onClick="testFunction('rightalign')" name="rightalign" id="rightalign" value="rightalign"/>
    </div>
    <script type="text/javascript">
    function testFunction(el){
        var testTextBox  =  document.getElementById("testBox");
        if(el == "centeralign"){
            testTextBox.style.textAlign = "center";
        }else if (el == "leftalign") {
            testTextBox.style.textAlign = "left";
        }else if (el == "rightalign") {
            testTextBox.style.textAlign = "right";
        }
    }
    </script>
</html>

这是IE中的一个奇怪错误(至少在某些版本中是这样)。当通过事件处理程序属性更改输入框的样式时,输入框呈现似乎不会更新。在testTextBox的定义之后添加以下内容似乎有帮助:

testTextBox.value += '';

这不会修改值,因为它会附加一个空字符串,但似乎足以唤醒IE,使其呈现具有更改样式的输入框。

如果你还没有解决问题,你可以随心所欲地在ie9测试的js代码中获得以下代码。。

    <!DOCTYPE html>
<html>
    <head>
        <title> Test for Text Align</title>
        <meta charset = "UTF-8" />
        <style type="text/css">
        #testBox{
            text-align: left;
        }
        </style>
    </head>
<body>
    <div>
        <input type="text" id ="testBox" name="testBox" value="testBox" maxlength="32" />
    </div>
    <div>
        <input type="button" onClick="testFunction('centeralign')" name="centeralign" id="centeralign" value="centeralign"/>
        <input type="button" onClick="testFunction('leftalign')" name="leftalign" id="leftalign" value="leftalign"/>
        <input type="button" onClick="testFunction('rightalign')" name="rightalign" id="rightalign" value="rightalign"/>
    </div>
    <script type="text/javascript">
    function testFunction(el){
        var testTextBox  =  document.getElementById("testBox");
        if(el == "centeralign"){
            testTextBox.style.textAlign = "center";
        }else if (el == "leftalign") {
            testTextBox.style.textAlign = "left";
        }else if (el == "rightalign") {
            testTextBox.style.textAlign = "right";
        }
    }
    </script>
</body>
</html>