Jquery-ui tooltip on click

2019-08-01 08:13发布

问题:

I'm trying to make a jquery-ui tooltip show/hide on a click event. Also I don't want it to show hide on mouse enter/leave.

Here is a fiddle with a normal tooltip : http://jsfiddle.net/Michael_0/sLhD9/ (unfortunately jsfiddle doesn't seem to be able to include jquery-ui from google cdn ?).

I had the idea to disabled the tooltip at initialization then enable it on click just before showing it, it works but I can't prevent the tooltip from hiding when the mouse leaves the target.

$("#myDiv").tooltip({
    disabled: true,
    content: function () {
        return "<div>Custom content</div>"
    }
});

$("#myDiv").click(function () {
        $(this).tooltip("option", "disabled", false);
        $(this).tooltip("open");
    });

回答1:

To do this you need to unbind the default event handlers:

$("#myDiv").unbind('mouseover');
$("#myDiv").attr('ttVisible','no');
$("#myDiv").click(function() {
    if($("#myDiv").attr('ttVisible') == 'no') {
        $("#myDiv").tooltip('open');
        $("#myDiv").unbind('mouseleave');
        $("#myDiv").attr('ttVisible','yes');
    } else {
        $("#myDiv").tooltip('close');
        $("#myDiv").attr('ttVisible','no');
    }
});

You can track the current state however works for you, I used an attribute called ttVisible. jQuery UI doesn't seem to expose the current state of the tooltip in any way.