我一直在尝试使用 jQuery 制作非常简单的 javascript 工具提示,但我遇到了障碍。这个想法是span在div. 该span元素将包含一个div带有小 html(图像和链接)的工具提示。单击元素时应打开工具提示,单击span元素外部或工具提示外部时应关闭工具提示。
到目前为止,打开工具提示不是问题,但关闭是问题。
<!DOCTYPE HTML>
<html>
<head>
    <title></title>
    <style>
        #colors > div {
            background-color: red;
            height: 50px;
            width: 50px;
            margin: 5px;
        }
        #colors > div > span {
            min-height: 10px !important;
            min-width: 10px !important;
            border: 3px solid black;
            position: relative;
        }
        .tooltip {
            border: 2px solid blue;
            display: none;
        }
    </style>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
    <script>
        $(function () {
            // generate boxes and tooltips
            for (var i = 0; i < 9; i++) {
                $('#colors').append('<div id="' + i + '"><span><div class="tooltip"><a href="#">add to favorites</a></div></span></div>');
            }
            $('#colors').delegate('span', 'click', function (event) {
                $(this).children('.tooltip').css({position:'absolute', top:'5px', left:'5px'}).fadeIn();
                // bottom one won't work
                //event.stopPropagation();
            });
            $(document).delegate('body', 'click', function (event) {
                var that = this
                $.each($('.tooltip'), function (index, element) {
                    // it's always visible ...
                    //if ($(element).is(':visible')) {
                    // doesn't work either
                    if ($(element).is(':visible') && $(element).has(event.target).length === 0) {
                        var s = event.target;
                        console.log([($(s) == event.target), event.target, index, element, $(element).has(event.target).length, that]);
                    }
                });
            });
        })
    </script>
</head>
<body>
<div id="colors"></div>
</body>
</html>
如果单击在工具提示之外,我似乎找不到关闭工具span提示的方法。