tips.js 1.48 KB
/**
 * Created by TaoHuang on 2016/7/1.
 */

var jQuery = require('yoho-jquery'),
    Handlebars = require('yoho-handlebars');

((function($) {

    var tpl = '<div class="tips hide">' +
        '<div class="triangle"></div>' +
        '<div class="rectangle"> {{content}}</div>' +
        '</div>';

    var tplFn = Handlebars.compile(tpl);

    var methods = {
        show: function() {
            var $parent = this.parent(),
                topLeft = $parent.offset(),
                $tips = this.find('.tips');

            if ($tips.length !== 0) {
                $tips.find('.rectangle').text(arguments[0]).removeClass('hide');
            } else {
                $parent.append(tplFn({content: arguments[0]}));
                $tips = $parent.find('.tips').removeClass('hide');
                $tips.css({
                    top: $parent.height() - 2,
                    left: topLeft.left,
                    width: this.width() + 2,
                    height: this.height
                });
            }

            return $tips;
        },
        hide: function() {
            var $parent = this.parent();

            return $parent.find('.tips').addClass('hide');
        }

    };

    $.fn.tips = function(method) {

        // 方法调用
        if (methods[method]) {
            return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
        } else {
            $.error('Method' + method + 'does not exist on jQuery.tooltip');
        }

    };

})(jQuery));