基于jquery实现一个提示插件

基于jquery实现一个提示插件

data-mode="top" data-tipTxet="自定义内容"
默认为显示传入元素内容,mode为bottom;

(function ($, window, document, undefined) {
  var modePos;
  $.fn.tip = function (options) {
    // 将对象合并到jq实例对象中
    var set = $.extend(
      {
        mode: "bottom",
        speed: 300,
        tipText: '提示内容',
      },
      options
    );
    if (!modePos) {
      //策略模式
      //算法
      modePos = {
        top: function (t, tip) {
          return {
            left: t.offset().left + (t.width() - tip.width()) / 2 + "px",
            top: t.offset().top - tip.height() - 12 + "px",
          };
        },
        bottom: function (t, tip) {
          return {
            left: this.top(t, tip).left,
            top: t.offset().top + t.height() + 12 + "px",
          };
        },
        left: function (t, tip) {
          return {
            left: t.offset().left - tip.width() - 12 + "px",
            top: t.offset().top + (t.height() - tip.height()) / 2 + "px",
          };
        },
        right: function (t, tip) {
          return {
            left: t.offset().left + t.width() + 12 + "px",
            top: t.offset().top + (t.height() - tip.height()) / 2 + "px",
          };
        },
      };
    }
    function Tip(_this) {
      var _that = $(_this);
      // 默认配置
      var _mode = set.mode; 
      var tipText = set.tipText;  
      
      var _tip = ".tip-container";
      // 自定义配置项
      if (_that.data("mode")) {
        _mode = _that.data("mode");
      }

      // 判断是否存在,存在的时候优先使用配置项
      if (_that.data("tip")) {
        tipText = _that.data("tip");
      } else {
        tipText = _that[0].innerText;
      }
      // 添加属性
      _that.css("cursor", "pointer");
      // 添加移入hover事件函数
      _that.hover(
        function () {
          var _tipHtml =
            '<div class="tip-container"><div class="tip-point-' +
            _mode +
            '"><div class="tip-content">' +
            tipText +
            "</div></div></div>";
          _that.removeAttr("title alt");
          $("body").append(_tipHtml);
          // 添加css位移
          $(_tip)
            .css(modePos[_mode](_that, $(_tip)))
            .fadeIn(set.speed);
        },
        function () {
          $(".tip-container").remove();
        }
      );
    }
    return this.each(function () {
      return new Tip(this);
    });
  };
})(jQuery, window, document);


 // $(".class").tip();

posted @ 2021-04-02 14:24  hello蔚蓝  阅读(95)  评论(0)    收藏  举报