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


Posted in Javascript onAugust 23, 2017

本组件依赖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验证框的实例代码,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对三水点靠木网站的支持!

Javascript 相关文章推荐
javascript Math.random()随机数函数
Nov 04 Javascript
JS.findElementById()使用介绍
Sep 21 Javascript
JQuery使用$.ajax和checkbox实现下次不在通知功能
Apr 16 Javascript
jQuery实现的导航动画效果(附demo源码)
Apr 01 Javascript
jQuery中的each()详细介绍(推荐)
May 25 Javascript
如何用JS判断两个数字的大小
Jul 21 Javascript
JavaScript实现简单的双色球(实例讲解)
Jul 31 Javascript
Vue.js实现按钮的动态绑定效果及实现代码
Aug 21 Javascript
在 Angular-cli 中使用 simple-mock 实现前端开发 API Mock 接口数据模拟功能的方法
Nov 28 Javascript
Vue项目中ESlint规范示例代码
Jul 04 Javascript
package.json中homepage属性的作用详解
Mar 11 Javascript
mpvue实现微信小程序快递单号查询代码
Apr 03 Javascript
利用Vue实现移动端图片轮播组件的方法实例
Aug 23 #Javascript
详解AngularJS跨页面传值(ui-router)
Aug 23 #Javascript
vue中页面跳转拦截器的实现方法
Aug 23 #Javascript
jquery.rotate.js实现可选抽奖次数和中奖内容的转盘抽奖代码
Aug 23 #jQuery
Angular2+国际化方案(ngx-translate)的示例代码
Aug 23 #Javascript
JS实现问卷星自动填问卷脚本并在两秒自动提交功能
Jun 17 #Javascript
简单实现jQuery上传图片显示预览功能
Jun 29 #jQuery
You might like
乐信RP2100的电路分析和打磨
2021/03/02 无线电
apache+php完美解决301重定向的两种方法
2011/06/08 PHP
采用ThinkPHP中F方法实现快速缓存实例
2014/06/13 PHP
PHP实现导出excel数据的类库用法示例
2016/10/15 PHP
thinkPHP框架实现类似java过滤器的简单方法示例
2018/09/05 PHP
ThinkPHP5.1表单令牌Token失效问题的解决
2019/03/22 PHP
javascript中使用replaceAll()函数实现字符替换的方法
2010/12/25 Javascript
JavaScript程序员应该知道的45个实用技巧
2014/03/04 Javascript
如何获取网站icon有哪些可行的方法
2014/06/05 Javascript
javascript工厂方式定义对象
2014/12/26 Javascript
jquery事件的ready()方法使用详解
2015/11/11 Javascript
实时监控input框,实现输入框与下拉框联动的实例
2018/01/23 Javascript
vue-cli脚手架引入图片的几种方法总结
2018/03/13 Javascript
Element-UI Table组件上添加列拖拽效果实现方法
2018/04/14 Javascript
JavaScript事件委托原理与用法实例分析
2018/06/07 Javascript
JS跨域请求的问题解析
2018/12/03 Javascript
JavaScript惰性载入函数实例分析
2019/03/27 Javascript
手写Vue弹窗Modal的实现代码
2019/09/11 Javascript
Echarts地图添加引导线效果(labelLine)
2019/09/30 Javascript
前端使用crypto.js进行加密的函数代码
2020/08/16 Javascript
js属性对象的hasOwnProperty方法的使用
2021/02/05 Javascript
[22:20]初生之犊-TI4第5名LGD战队纪录片
2014/08/13 DOTA
Python实现简单拆分PDF文件的方法
2015/07/30 Python
Python实现excel转sqlite的方法
2017/07/17 Python
python实现单向链表详解
2018/02/08 Python
Python设计模式之装饰模式实例详解
2019/01/21 Python
python对常见数据类型的遍历解析
2019/08/27 Python
Python实现检测文件的MD5值来查找重复文件案例
2020/03/12 Python
用HTML5 Canvas API中的clearRect()方法实现橡皮擦功能
2016/03/15 HTML / CSS
购买大码女装:Lane Bryant
2016/09/07 全球购物
Stuart Weitzman欧盟:美国奢华鞋履品牌
2017/05/24 全球购物
在购买印度民族服饰:Soch
2020/09/15 全球购物
思想品德自我鉴定
2013/10/12 职场文书
幼儿教师寄语集锦
2014/04/03 职场文书
2016高三毕业赠言寄语
2015/12/04 职场文书
Python深度学习之Pytorch初步使用
2021/05/20 Python