简体   繁体   中英

Left align text input onblur (IE 8 & 9)

I am looking for a method to left align the contents of a text input box when the user fires the onblur event. I have seen mention of solving the issue with onblur="this.value = this.value", but this does not work in IE.

To Clarify: This issue occurs in Internet Explorer when the user types beyond the width of the textbox and then leaves focus. In Chrome and Firefox, the text will automatically left align, but this does not happen in IE.

Due to request, I've attached code (View in IE):

<input type="text" />

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

Text Field:

文本域

After Typing:

键入后

After Blur:

模糊后

How it should look:

它看起来如何

This is rather a hack than a proper solution, but somehow it works:

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);" />

Notice the use of onchange instead of onblur . This is since select() causes some troubles when using onblur .

Here is a jQuery version I mocked up that works in all the major browsers:

$(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 ??
            }
        });
});

I'd just set a class on that field and then fire up a function with the onBlur in your html: eg onBlur="left()" Then in your javascript you can then simply change the class with .setAttribute As an added bonus you can also set other properties for that class as well.

Although I do support the notion of posting relevant code

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM