簡體   English   中英

左對齊文本輸入法(IE 8和9)

[英]Left align text input onblur (IE 8 & 9)

我正在尋找一種在用戶觸發onb​​lur事件時使文本輸入框的內容左對齊的方法。 我已經看到過用onblur =“ this.value = this.value”解決問題的提法,但這在IE中不起作用。

澄清:當用戶鍵入超出文本框寬度,然后離開焦點時,在Internet Explorer中會發生此問題。 在Chrome和Firefox中,文本將自動左對齊,但這在IE中不會發生。

根據要求,我附上了代碼(在IE中查看):

<input type="text" />

http://jsfiddle.net/t3hjonneh/FZJjW/

文本域:

文本域

鍵入后:

鍵入后

模糊后:

模糊后

外觀如何:

它看起來如何

這是一個hack,而不是一個適當的解決方案,但是以某種方式起作用:

function blurred(elem) {
    var range;
    // IE only, probably not the best check since it will run in other browsers
    // if they ever implement this feature
    if (elem.createTextRange) {
        range = elem.createTextRange();
        range.collapse(true);
        range.select();
    }
}

<input type="text" onchange="blurred(this);" />

注意使用onchange而不是onblur 這是因為在使用onblurselect()會引起一些麻煩。

這是我模擬的適用於所有主要瀏覽器的jQuery版本:

$(document).ready(function(){
        $('input[type=text]').change(function(){
            try{//select nothing but side-effect is that text left justifies
                if(/webkit/.test(navigator.userAgent.toLowerCase())){
                    return;//webkit browsers do it automatically
                } else if(this.createTextRange) { //ie
                    var r = this.createTextRange();
                    r.collapse(true);
                    r.select();
                } else if(typeof this.selectionStart !== "undefined") { //firefox
                    this.selectionStart = 0;
                    this.selectionEnd = 0;
                }
            } catch(err) {
            //?? nobody cares ??
            }
        });
});

我只是在該字段上設置了一個類,然后使用html中的onBlur觸發了一個函數:例如, onBlur="left()"然后在您的javascript中,您可以簡單地使用.setAttribute更改該類。也可以為該類設置其他屬性。

盡管我支持發布相關代碼的想法

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM