/* 事件綁定 */ var addEvent = document.addEventListener ? function(element, type, fn) { element.addEventListener(type, fn, false); } : function(element, type, fn) { element.attachEvent("on" + type, fn); }, /* 事件解除綁定 */ removeEvent = document.removeEventListener ? function(element, type, fn) { element.removeEventListener(type, fn, false); } : function(element, type, fn) { element.detachEvent("on" + type, fn); }, /* 文字框浮水印/預留位置 */ watermark = function(element, text) { if (!(this instanceof watermark)) return new watermark(element, text); var place = document.createElement("span");//提示資訊標記 element.parentNode.insertBefore(place, element);//插入到表單元素之前的位置 place.className = "w-label"; place.innerHTML = text; place.style.height = place.style.lineHeight = element.offsetHeight + "px";//設定高度、行高以置中 element.place = this; function hideIfHasValue() { if (element.value && place.className.indexOf("w-hide") == -1) place.className += " w-hide"; } function onFocus() { hideIfHasValue() if (!element.value && place.className.indexOf("w-active") == -1) place.className += " w-active"; } function onBlur() { if (!element.value) { place.className = place.className.replace(" w-active", ""); place.className = place.className.replace(" w-hide", ""); } } function onClick() { hideIfHasValue(); try { element.focus && element.focus(); } catch (ex) {} } // 註冊各個事件 hideIfHasValue(); addEvent(element, "focus", onFocus); addEvent(element, "blur", onBlur); addEvent(element, "keyup", hideIfHasValue); addEvent(place, "click", onClick); // 取消watermark this.unload = function() { removeEvent(element, "focus", onFocus); removeEvent(element, "blur", onBlur); removeEvent(element, "keyup", hideIfHasValue); removeEvent(place, "click", onClick); element.parentNode.removeChild(place); element.place = null; }; }; |