插件没有响应动作:悬停

时间:2013-10-27 11:36:53

标签: jquery css

我的插件有很多代码,如下所示:

var element = $("*[data-label]");
(function ($) {
    $.fn.Label = function (options) {
        var label = $(this).attr("data-label"),
            d = document.createElement('span'),
            t = document.createTextNode(label),
            config = $.extend({
            display: 'inline',
            position: 'absolute',
            top: '6.5em',
            padding: '0.5em',
            backgroundColor: '#383838',
            color: 'white',
            fontSize: '0.8em',
            opacity: '0.9',
        }, options);
        if (element.is(":hover")) {
            d.className = "labelShow";
            $(this).append(d);
            $('.labelShow').append(t).css(config);
        } else {
            $(".labelShow").remove();
            return false;
        }
    };

}(jQuery));

element.Label();

我在控制台中没有错误,并且调试器在我悬停元素时没有捕获任何事件我想响应我的小部件代码。你能不能给我任何暗示,为什么它不起作用?

1 个答案:

答案 0 :(得分:2)

尝试

(function ($) {
    $.fn.Label = function (options) {
        //create a shared css def for the label
        var css = $.extend({
            display: 'inline',
            position: 'absolute',
            top: '6.5em',
            padding: '0.5em',
            backgroundColor: '#383838',
            color: 'white',
            fontSize: '0.8em',
            opacity: '0.9'
        }, options);

        //append the label span to each element in the jquery element set on which the plugin was initialized
        this.append(function () {
            return $('<span />', {
                text: $(this).data('label'),
                'class': 'labelShow'
            }).css(css).hide();
        //register mouser enter and mouse leave events for each of the elements so that the label can be displayed or hidden
        }).hover(function () {
            $(this).find('.labelShow').show();
        }, function () {
            $(this).find('.labelShow').hide();
        });
    };

})(jQuery);

var element = $("*[data-label]");
element.Label();

演示:Fiddle