欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

使用JS组件实现带ToolTip验证框的实例代码

程序员文章站 2022-04-29 08:12:44
本组件依赖jquery 本人测试的jquery 是1.8, 兼容ie8,ie9,谷歌,火狐等。 //验证输入框 function validatecompe...

本组件依赖jquery

本人测试的jquery 是1.8,

兼容ie8,ie9,谷歌,火狐等。

//验证输入框
function validatecompent(input){
  var _input = $(input).clone(true);
  _input.css("height",$(input).css("height"));
  _input.css("width", $(input).css("width"));
  var border =_input.css("border"); 
  this.successiconclass = "icon-tick";//验证通过时的样式
  this.validate = false;
  this.faileiconclass = "icon-times";//验证失败时的样式
  var $validateroot = $('<div class="validate-v1-container"><div class="validate-v1-tooltip"></div></div>');
  var $tooltip = $validateroot.children(".validate-v1-tooltip");
  var $input = _input;
  if($input != undefined){
    var maxwidth = $input.css("width");
    var maxheight = $input.css("height");
    $validateroot.css("display","inline");
    $validateroot.css("position","relative");
    $validateroot.css("width",maxwidth);
    $validateroot.css("height",maxheight);
    $tooltip.css("width",maxwidth);
    $tooltip.css("padding","0px 5px");
    $tooltip.css("position","absolute");
    $tooltip.css("top","0px");
    $tooltip.css("z-index","999999");
    $tooltip.css("background-color","white");
    $tooltip.css("border","solid 1px rgb(188,188,188)");
    $tooltip.css("left",parseint(maxwidth) + 10+"px");
    $tooltip.hide();
    var validateoption = $input.attr("data-vali-option");
    if(validateoption != undefined){
      validateoption = json.parse(validateoption);
      var that = this;
      var regvali = new array();
      $tooltip.hide();
      if(validateoption.length == 0){
        return;
      }
      for(var i = 0; i <validateoption.length;i++){
        var message = validateoption[i].message;
        var pattern = validateoption[i].pattern;
        var reg = new regexp(pattern);
        var messageview = new validatemessage(message,that.faileiconclass);
        regvali.push({"reg":reg,"view":messageview});
        $tooltip.append(messageview.dom);
      }
      $tooltip.css("height",(parseint(maxheight) +15) * validateoption.length );
      $input.on("textchange focus",function(e){
        $tooltip.show();
        for(var i = 0 ; i < regvali.length; i++){
          if(regvali[i].reg.test($input.val())){
            regvali[i].view.seticonclass(that.successiconclass);
            regvali[i].view.dom.css("color","green");
          }else{
            regvali[i].view.seticonclass(that.faileiconclass);
            regvali[i].view.dom.css("color","red");
          }
        }
      })
      $input.on("blur", function(e) {
        $tooltip.hide();
        for(var i = 0 ; i < regvali.length; i++){
          if(regvali[i].reg.test($input.val())){
            regvali[i].view.seticonclass(that.successiconclass);
            $input.css("border",border);
            that.validate = true;
          }else{
            regvali[i].view.seticonclass(that.faileiconclass);
            $input.css("border","1px solid red");
            that.validate = false;
            break;
          }
        }
      });
      $validateroot.append($input);
    }else{
      return;
    }
  }
  this.dom = function(){
    return $validateroot;
  }
  function validatemessage(message,iconfontclass){
    var dom = $('<div class="validate-message"><span class="vticon"></span><span class="vmessage"></span></div>');
    var $icon = dom.children(".vticon");
    var $message = dom.children(".vmessage");
    $message.css("line-height","28px");
    $message.css("padding","5px 5px");
    $message.css("padding-right","10px");
    $message.css("word-break","break-all");
    $message.css("word-wrap","break-word");
    $message.css("font-size","14px");
    $message.css("position","relative");
    $message.css("z-index","999999");
    this.seticonclass = function(iconclass){
      $icon.removeclass();
      $icon.addclass("vticon");
      $icon.addclass(iconclass);
    }
    this.geticon = function(){
      return $icon;
    }
    this.setmessagetext = function(_message){
      $message.html(_message);
    }
    this.getmessagetext = function(){
      return $message;
    }
    this.seticonclass(iconfontclass);
    this.setmessagetext(message);
    this.dom = dom;
  }
  $validateroot.insertafter($(input));
  $(input).remove();
}

以下是html代码

<input id="test" data-vali-option='[{"pattern":"[1-9]+","message":"只能输入1-9的数"},{"pattern":"[a-z]+","message":"只能输入a-z的数"}]' />

使用方法如下

$(function(){
  var c = new validatecompent("#test");
});

依赖jquery,

另外附上jquery textchange事件的代码,textchange代码放在jquery之后,在使用方法之前。

/**
 * jquery "splendid textchange" plugin
 * http://benalpert.com/2013/06/18/a-near-perfect-oninput-shim-for-ie-8-and-9.html
 *
 * (c) 2013 ben alpert, released under the mit license
 */
(function($) {
var testnode = document.createelement("input");
var isinputsupported = "oninput" in testnode && 
  (!("documentmode" in document) || document.documentmode > 9);
var hasinputcapabilities = function(elem) {
  // the html5 spec lists many more types than `text` and `password` on
  // which the input event is triggered but none of them exist in ie 8 or
  // 9, so we don't check them here.
  // todo: <textarea> should be supported too but ie seems to reset the
  // selection when changing textarea contents during a selectionchange
  // event so it's not listed here for now.
  return elem.nodename === "input" &&
    (elem.type === "text" || elem.type === "password");
};
var activeelement = null;
var activeelementvalue = null;
var activeelementvalueprop = null;
/**
 * (for old ie.) replacement getter/setter for the `value` property that
 * gets set on the active element.
 */
var newvalueprop = {
  get: function() {
    return activeelementvalueprop.get.call(this);
  },
  set: function(val) {
    activeelementvalue = val;
    activeelementvalueprop.set.call(this, val);
  }
};
/**
 * (for old ie.) starts tracking propertychange events on the passed-in element
 * and override the value property so that we can distinguish user events from
 * value changes in js.
 */
var startwatching = function(target) {
  activeelement = target;
  activeelementvalue = target.value;
  activeelementvalueprop = object.getownpropertydescriptor(
      target.constructor.prototype, "value");
  object.defineproperty(activeelement, "value", newvalueprop);
  activeelement.attachevent("onpropertychange", handlepropertychange);
};
/**
 * (for old ie.) removes the event listeners from the currently-tracked
 * element, if any exists.
 */
var stopwatching = function() {
 if (!activeelement) return;
 // delete restores the original property definition
 delete activeelement.value;
 activeelement.detachevent("onpropertychange", handlepropertychange);
 activeelement = null;
 activeelementvalue = null;
 activeelementvalueprop = null;
};
/**
 * (for old ie.) handles a propertychange event, sending a textchange event if
 * the value of the active element has changed.
 */
var handlepropertychange = function(nativeevent) {
  if (nativeevent.propertyname !== "value") return;
  var value = nativeevent.srcelement.value;
  if (value === activeelementvalue) return;
  activeelementvalue = value;
  $(activeelement).trigger("textchange");
};
if (isinputsupported) {
  $(document)
    .on("input", function(e) {
      // in modern browsers (i.e., not ie 8 or 9), the input event is
      // exactly what we want so fall through here and trigger the
      // event...
      if (e.target.nodename !== "textarea") {
        // ...unless it's a textarea, in which case we don't fire an
        // event (so that we have consistency with our old-ie shim).
        $(e.target).trigger("textchange");
      }
    });
} else {
  $(document)
    .on("focusin", function(e) {
      // in ie 8, we can capture almost all .value changes by adding a
      // propertychange handler and looking for events with propertyname
      // equal to 'value'.
      // in ie 9, propertychange fires for most input events but is buggy
      // and doesn't fire when text is deleted, but conveniently,
      // selectionchange appears to fire in all of the remaining cases so
      // we catch those and forward the event if the value has changed.
      // in either case, we don't want to call the event handler if the
      // value is changed from js so we redefine a setter for `.value`
      // that updates our activeelementvalue variable, allowing us to
      // ignore those changes.
      if (hasinputcapabilities(e.target)) {
        // stopwatching() should be a noop here but we call it just in
        // case we missed a blur event somehow.
        stopwatching();
        startwatching(e.target);
      }
    })
    .on("focusout", function() {
      stopwatching();
    })
    .on("selectionchange keyup keydown", function() {
      // on the selectionchange event, e.target is just document which
      // isn't helpful for us so just check activeelement instead.
      //
      // 90% of the time, keydown and keyup aren't necessary. ie 8 fails
      // to fire propertychange on the first input event after setting
      // `value` from a script and fires only keydown, keypress, keyup.
      // catching keyup usually gets it and catching keydown lets us fire
      // an event for the first keystroke if user does a key repeat
      // (it'll be a little delayed: right before the second keystroke).
      // other input methods (e.g., paste) seem to fire selectionchange
      // normally.
      if (activeelement && activeelement.value !== activeelementvalue) {
        activeelementvalue = activeelement.value;
        $(activeelement).trigger("textchange");
      }
    });
}
})(jquery);

获取验证结果

$(function(){
  var c = new validatecompent("#test");
  $("#test").click(function(){
    console.log(c.validate);
  });
});

自定义显示方案

$(function(){
  var c = new validatecompent("#test");
  $("#test").click(function(){
    console.log(c.validate);
  });
  c.dom().addclass("你的样式类");
});

设置图标字体样式

$(function(){
  var c = new validatecompent("#test");
  $("#test").click(function(){
    console.log(c.validate);
  });
  c.successiconclass = "";//成功时的样式
  c.faileiconclass = "";//失败时的样式
});

效果图如下

分别是成功,部分成功,全部失败选中,未选中的样式效果,(勾叉是用的字体css,建议自行寻找字体替代)

使用JS组件实现带ToolTip验证框的实例代码使用JS组件实现带ToolTip验证框的实例代码使用JS组件实现带ToolTip验证框的实例代码使用JS组件实现带ToolTip验证框的实例代码

总结

以上所述是小编给大家介绍的使用js组件实现带tooltip验证框的实例代码,希望对大家有所帮助