簡體   English   中英

jQuery Blur()無法與click()函數一起使用

[英]jQuery Blur() not working with click() function

我試圖使帶有內容的工具提示在我單擊外部時消失,但是嘗試了針對不同帖子的解決方案,但這些解決方案都不適合我。

我認為問題是我如何觸發工具提示,但這是我知道的唯一方法,這是我在js和html標記中擁有的代碼。

工具提示可以很好地觸發,但是無論如何,它都不能與模糊事件一起使用。

$(document).ready(function() {

    function tooltover(target_item){
        $(target_item + '> a').click(function(){
            $('.tiptover_box').focus();

            var pos = $(this).position();
            var width = $(this).outerWidth();
            var boxw = $(this).next().outerWidth();
            var boxh = $(this).next().outerHeight();

            $(this).next().css('left', (pos.left - ((boxw/2)-(width/2))));
            $(this).next().css('top', (pos.top - (boxh+5)));
            $(this).next().addClass('tiptover_show');
            $(this).next().delay(5).queue(function(){
                $(this).addClass('tt-in');
                $(this).dequeue();
            });
        });
        $('.tiptover_box').blur( function(){
            $('.tiptover_box').removeClass('tiptover_show tt-in');
        });
    } tooltover('.tiptover');

});

HTML

<div class="tiptover">
    <a>Link Test</a>
    <div class="tiptover_box" style="background-image: url(content/prod_0002.jpg);">
        <div>Description.</div>
    </div>
</div>

另一種方法是不關注div本身,而是關注DOM的其余部分。

prc322針對類似問題給出的解決方案中 ,他在document本身上使用了mouseup事件:

$(document).mouseup(function (e)
{
    var container = $(".tiptover_box");

    if (!container.is(e.target) // if the target of the click isn't the container...
        && container.has(e.target).length === 0) // ... nor a descendant of the container
    {
        container.removeClass('tiptover_show tt-in');
    }
});

(由我進行相關性編輯)

現在,只要在非.tiptover_box或其任何后代的任何元素上觸發mouseup事件,您的工具提示都會“關閉”。

無需嘗試觸發div的blur事件(可靠性不如模糊輸入字段那樣可靠),而是可以執行所需的操作-單擊任何內容時,您都可以隱藏工具提示:

$('body').click(function(e){
        var tooltipContainer = $('.tiptover_box');
        var clickTarget = e.target;

        if(!tooltipContainer.is(clickTarget)
          && tooltipContainer.has(clickTarget).length === 0){
            tooltipContainer.removeClass('tiptover_show tt-in');
        }
});

編輯:增加了對容器及其子級的測試,基本上與鮑勃的答案相同。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM