html onchange/onblur compatibility

冷暖自知 提交于 2019-12-01 08:39:08
Dan Herbert

All browsers should support these events pretty decently if you're only using them in text boxes. If you check out the QuirksMode event compatibility tables, you'll see that IE has some issues with the change event in radio buttons and check boxes.

If you're not very familiar with JavaScript events in browsers, you'll find that the event model is a mess thanks to the fact that IE decided to do things differently from the standard. To overcome this problem, you should be using a JavaScript framework like jQuery, YUI, Dojo, MooTools, ExtJS, or Closure. These frameworks smooth out the differences so you'll (almost) never have to deal with the differences & bugs in the different browsers. There is a great article on CodingHorror explaining why you should consider using a JavaScript framework if you plan on using JavaScript in your site that you should read if you're curious as to why you should use a JavaScript framework.

Also, if you're unfamiliar with browser events entirely, make sure you understand the difference between onchange and onblur.

I believe there are no more problem with these two specific events than with all events in Internet Explorer plus the usual weird quirks such as this one.

The general solution to event-handling and MANY other problems is to use a Javascript framework whose developers have bled their own blood to save yours, papering over all IE (and a few other) weirdnesses, such as dojo. As the Dojo folks say on that page:

The word "support" means something very specific for Dojo and Dijit, in that saying that Dojo Core and Dijit support a browser means that 100% of the available functionality works, that accessibility is handled correctly, and that all internationalization and localization is supported. This is a very high bar, which also means that while we may not saying that browsers like Opera are "supported" for Dijit, it's highly likely that it will all work there too, but there may be some caveat which we were not able to work around (such as accessibility hook on Opera).

The browsers they claim as "supported" at this very-high-bar level are (as of Dojo 1.3.2) IE 6 to 8, Safari 3.1 to 4, Firefox 2 to 3.5, Chrome 1 to 2 (core functionality, including event handling, also works on Opera, Konqueror, FF 1.5, ...).

If you use jQuery, try this:

$('input.text').click(function () {
        if (this.value == this.defaultValue) {
            this.value = '';
        }
    });
    $('input.text').blur(function () {
        if (this.value === '') {
            this.value = this.defaultValue;
        }
    });

$("input:text") if you want to target all text input fields.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!