호버링하는 동안 부트 스트랩 팝 오버를 유지하려면 어떻게해야합니까?


114

부트 스트랩 팝 오버를 사용하여 사용자 정보를 표시하는 호버 카드를 만들고 버튼을 마우스 오버하면 트리거합니다. 팝 오버 자체가 호버링되는 동안이 팝 오버를 유지하고 싶지만 사용자가 버튼 위로 마우스를 가져가는 것을 멈 추면 즉시 사라집니다. 어떻게 할 수 있습니까?

$('#example').popover({
    html : true,
    trigger : 'manual',
    content : function() {
        return '<div class="box">Popover</div>';
    }
});

$(document).on('mouseover', '#example', function(){
    $('#example').popover('show');
});

$(document).on('mouseleave', '#example', function(){
    $('#example').popover('hide');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.js"></script>
<script src="https://unpkg.com/@popperjs/core@2"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"/>

<a href="#" id="example" class="btn btn-danger" rel="popover" >hover for popover</a>


무엇을 유지하고 싶습니까? 버튼 위로 마우스를 가져가도 계속 열려 있습니까?
David Chase

질문의 마지막 줄을 읽고
카스 devde

답변:


172

아래 코드 조각으로 테스트하십시오.

내 사용 사례에 맞게 (vikas에서 제공하는 솔루션에서) 작은 수정.

  1. 팝 오버 버튼에 대한 호버 이벤트시 팝 오버 열기
  2. 팝 오버 상자 위로 마우스를 가져갈 때 팝 오버를 열어 둡니다.
  3. 팝 오버 버튼 또는 팝 오버 상자에 대해 mouseleave시 팝 오버를 닫습니다.

$(".pop").popover({
    trigger: "manual",
    html: true,
    animation: false
  })
  .on("mouseenter", function() {
    var _this = this;
    $(this).popover("show");
    $(".popover").on("mouseleave", function() {
      $(_this).popover('hide');
    });
  }).on("mouseleave", function() {
    var _this = this;
    setTimeout(function() {
      if (!$(".popover:hover").length) {
        $(_this).popover("hide");
      }
    }, 300);
  });
<!DOCTYPE html>
<html>

<head>
  <link data-require="bootstrap-css@*" data-semver="3.2.0" rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" />
  <script data-require="jquery@*" data-semver="2.1.1" src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
  <script data-require="bootstrap@*" data-semver="3.2.0" src="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.js"></script>

  <link rel="stylesheet" href="style.css" />

</head>

<body>
  <h2 class='text-primary'>Another Great "KISS" Bootstrap Popover example!</h2>
  <p class='text-muted'>KISS = Keep It Simple S....</p>

  <p class='text-primary'>Goal:</p>
  <ul>
    <li>Open popover on hover event for the popover button</li>
    <li>Keep popover open when hovering over the popover box</li>
    <li>Close popover on mouseleave for either the popover button, or the popover box.</li>
  </ul>

  <button type="button" class="btn btn-danger pop" data-container="body" data-toggle="popover" data-placement="right" data-content="Optional parameter: Skip if this was not requested<br>                                    A placement group is a logical grouping of instances within a single Availability                                     Zone. Using placement groups enables applications to get the full-bisection bandwidth                                     and low-latency network performance required for tightly coupled, node-to-node                                     communication typical of HPC applications.<br>                                    This only applies to cluster compute instances: cc2.8xlarge, cg1.4xlarge, cr1.8xlarge, hi1.4xlarge and hs1.8xlarge.<br>                                    More info: <a href=&quot;http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/placement-groups.html&quot; target=&quot;_blank&quot;>Click here...</a>"
    data-original-title="" title="">
    HOVER OVER ME
    </button>
  <br><br>
  <button type="button" class="btn btn-info pop" data-container="body" data-toggle="popover" data-placement="right" data-content="Optional parameter: Skip if this was not requested<br>                                    A placement group is a logical grouping of instances within a single Availability                                     Zone. Using placement groups enables applications to get the full-bisection bandwidth                                     and low-latency network performance required for tightly coupled, node-to-node                                     communication typical of HPC applications.<br>                                    This only applies to cluster compute instances: cc2.8xlarge, cg1.4xlarge, cr1.8xlarge, hi1.4xlarge and hs1.8xlarge.<br>                                    More info: <a href=&quot;http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/placement-groups.html&quot; target=&quot;_blank&quot;>Click here...</a>"
    data-original-title="" title="">
    HOVER OVER ME... Again!
    </button><br><br>
  <button type="button" class="btn btn-success pop" data-container="body" data-toggle="popover" data-placement="right" data-content="Optional parameter: Skip if this was not requested<br>                                    A placement group is a logical grouping of instances within a single Availability                                     Zone. Using placement groups enables applications to get the full-bisection bandwidth                                     and low-latency network performance required for tightly coupled, node-to-node                                     communication typical of HPC applications.<br>                                    This only applies to cluster compute instances: cc2.8xlarge, cg1.4xlarge, cr1.8xlarge, hi1.4xlarge and hs1.8xlarge.<br>                                    More info: <a href=&quot;http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/placement-groups.html&quot; target=&quot;_blank&quot;>Click here...</a>"
    data-original-title="" title="">
    Okay one more time... !
    </button>
  <br><br>
  <p class='text-info'>Hope that helps you... Drove me crazy for a while</p>
  <script src="script.js"></script>
</body>

</html>


이것은 완벽하게 작동합니다 . ;두 번째 로 누락 된 부분이 있음을 알았습니다 $(_this).popover("hide"). 그러나 감사합니다. 너무 간단하고 깨끗했습니다!
scapegoat17

3
이 대답은 놀랍습니다. 2015 년 5 월 현재 BS3에서 훌륭하게 작동합니다 ^^
퇴화

1
나는 그것을 표에서 사용 container: 'body'했고 셀을 이동시키기 때문에 옵션에 추가 했습니다. 좋은 대답입니다!
Alexander Derck

팝 오버를 입력 한 다음 300ms 이전에 트리거 요소로 돌아 가면 팝 오버가 숨겨집니다. 이 문제를 해결하려면 setTimeout에서 숨기기 전에 팝 오버와 트리거가 모두 : hover인지 확인하십시오. 나는 또한 setTimeout과 동일한 접근 방식을 mouseleave에서 팝 오버 자체를 사용하여 깜박임을 수정합니다.
rzb

animation:false깜박임을 수정 하도록 설정하십시오 . 위의 Plunker 링크를 확인하십시오. 그것은 나를 위해 완벽하게 작동합니다.
OkezieE 2016 년

84

나는 이것에 대한 또 다른 해결책을 찾았습니다 ... 여기에 코드가 있습니다.

    $('.selector').popover({
        html: true,
        trigger: 'manual',
        container: $(this).attr('id'),
        placement: 'top',
        content: function () {
            $return = '<div class="hover-hovercard"></div>';
        }
    }).on("mouseenter", function () {
        var _this = this;
        $(this).popover("show");
        $(this).siblings(".popover").on("mouseleave", function () {
            $(_this).popover('hide');
        });
    }).on("mouseleave", function () {
        var _this = this;
        setTimeout(function () {
            if (!$(".popover:hover").length) {
                $(_this).popover("hide")
            }
        }, 100);
    });

6
추가하는 것이 중요하다 animation: false반복이 제대로 작동하지하게됩니다 링크 위로 마우스를 이동, 그렇지 않으면
jasop

5
@vikas ( gist.github.com/Nitrodist/7913848 ) 코드를 약간 수정했습니다 . 50ms 후에 상태를 다시 확인하여 열린 상태로 유지되지 않도록합니다. 즉, 50ms마다 지속적으로 재확인합니다.
Nitrodist

2
문서에 방금 추가 된 라이브 요소에서 작동하도록 어떻게 조정할 수 있습니까?
williamsowen 2014 년

28

내 의견은 다음과 같습니다. http://jsfiddle.net/WojtekKruszewski/Zf3m7/22/

때때로 마우스를 팝 오버 트리거에서 실제 팝 오버 콘텐츠로 대각선으로 이동하는 동안 아래 요소 위로 마우스를 가져갑니다. 이러한 상황을 처리하고 싶었습니다. 타임 아웃이 시작되기 전에 팝 오버 콘텐츠에 도달하는 한 안전합니다 (팝 오버가 사라지지 않음). delay옵션 이 필요합니다 .

이 해킹은 기본적으로 Popover leave기능을 재정의 하지만 원본을 호출합니다 ( 팝 오버 를 숨기기 위해 타이머를 시작 함). 그런 다음 mouseenter팝 오버 콘텐츠 요소에 일회용 리스너를 연결합니다 .

마우스가 팝 오버에 들어가면 타이머가 지워집니다. 그런 다음 mouseleave팝 오버시 청취하고 트리거되면 원래의 나가기 기능을 호출하여 타이머 숨기기를 시작할 수 있습니다.

var originalLeave = $.fn.popover.Constructor.prototype.leave;
$.fn.popover.Constructor.prototype.leave = function(obj){
  var self = obj instanceof this.constructor ?
    obj : $(obj.currentTarget)[this.type](this.getDelegateOptions()).data('bs.' + this.type)
  var container, timeout;

  originalLeave.call(this, obj);

  if(obj.currentTarget) {
    container = $(obj.currentTarget).siblings('.popover')
    timeout = self.timeout;
    container.one('mouseenter', function(){
      //We entered the actual popover – call off the dogs
      clearTimeout(timeout);
      //Let's monitor popover content instead
      container.one('mouseleave', function(){
        $.fn.popover.Constructor.prototype.leave.call(self, self);
      });
    })
  }
};

5
container = self.$tip;이 방법 을 사용하여 컨테이너 찾기를 개선 할 수 있습니다 container. 속성이 설정되어 있을 때도 팝 오버를 찾을 수 있습니다 . 바이올린은 여기있다 : jsfiddle.net/dennis_c/xJc65이
dbroeks

3
@pferrel 나는 @Wojtek_Kruszewski의 바이올린 포크 에서이 문제를 해결했습니다. jsfiddle.net/HugeHugh/pN26dif (!thisTip.is(':visible')) 를 호출하기 전에 확인하는 부분을 참조하십시오originalShow()
H Dog

1
옵션으로 팝 오버가 초기화되면 container: 'body',이 솔루션이 예상대로 작동하지 않습니다. 변수 container를로 바꿔야합니다 self.$tip. 자세한 내용은 내 대답을 확인하십시오. stackoverflow.com/a/28731847/439427
Rubens Mariuzzo

1
훌륭한. 이것은 다른 답변과 달리 'selector'매개 변수를 사용할 때 작동합니다.
jetlej

1
여기서 떠나 선단이 아직도 가리는 재진입시 버그 해결하는 개선 된 버전이고, 또한 선단부가 본체에 장착 될 때 시나리오를 해결 jsfiddle.net/Zf3m7/1499
졸탄 Tamási

14

쉬운 방법은 다음과 같습니다.

$('.popover').each(function () {
                    var $this = $(this);
                    $this.popover({
                        trigger: 'hover',
                        content: 'Content Here',
                        container: $this
                    })
                });

이렇게하면 팝 오버가 대상 요소 자체 내에 생성됩니다. 따라서 마우스를 팝 오버 위로 이동해도 여전히 요소 위에 있습니다. Bootstrap 3.3.2는 이것과 잘 작동합니다. 이전 버전은 애니메이션에 문제가있을 수 있으므로 "animation : false"를 비활성화하는 것이 좋습니다.


나는이 스레드가 오래되었다는 것을 알고 있지만 이것은 내 생각에 가장 좋고 깨끗한 솔루션이며 더 높은 순위를 매겨 야한다. 유일한주의 사항은 팝 오버를 트리거 요소에서 "멀리"(이상하게) 배치하면 이것이 깨질 수 있다는 것입니다. 그러나 둘 사이의 거리가 0 인 한 (예 : 겹침) 이것은 아름답게 작동하며 사용자 정의 JS가 필요하지 않습니다. 감사합니다!
JohnGalt

이것이 지금까지 가장 좋고 깨끗하며 가장 쉬운 솔루션입니다. 더 높은 순위 여야합니다! 나는 추가 delay: { "hide": 400 }숨어 전에 약간의 지연을 추가하고 그것을 잘 작동합니다! 👍
coorasse

14

나는 트리거 세트를 사용 hover하고 컨테이너받는 세트 준 #element의 배치 추가 마침내과 box에를 right.

이것이 귀하의 설정이어야합니다.

$('#example').popover({
    html: true,
    trigger: 'hover',
    container: '#example',
    placement: 'right',
    content: function () {
        return '<div class="box"></div>';
    }
});

#exampleCSS를 요구 position:relative;jsfiddle 아래를 확인 :

https://jsfiddle.net/9qn6pw4p/1/

수정 됨

이 바이올린에는 문제없이 작동하는 두 링크가 모두 있습니다. http://jsfiddle.net/davidchase03/FQE57/4/


작동하는 흠, content옵션 에서 jquery ajax를 사용 하여 서버 측에서 콘텐츠를 가져올 수 있습니까? 그 작업을 수행하거나 추가 작업을 수행해야합니다
vikas devde 2013

@vikasdevde 예 사용할 수있는 ajax내용이 아니라 당신이 일에 그에 대한 설정까지 할 필요가 ... 그것은 당신의 해결 바로 경우 대답을 표시하십시오 OP다른 사람들이 혜택을 누릴 수 있도록 ..
데이비드 체이스

우리는 전체 팝 오버가 링크되고 다음 컨테이너로 링크 자체를 사용하는 경우하지만 .... 그것을 시도
카스 devde

상자 안에 링크를 넣으면 여전히 링크가됩니다. 맞습니까?
David Chase

2
나를 위해 jsfiddle의 작업은 없습니다. Chrome 2014 년 3 월 20 일.
pferrel

7

이것이 내가 네트워크 주변의 다른 비트의 도움으로 부트 스트랩 팝 오버로 한 방법입니다. 사이트에 표시되는 다양한 제품에서 제목과 콘텐츠를 동적으로 가져옵니다. 각 제품 또는 팝 오버는 고유 한 ID를 갖습니다. 팝 오버는 제품 ($ this .pop) 또는 팝 오버를 종료 할 때 사라집니다. 타임 아웃은 팝 오버 대신 제품을 통과 할 때까지 팝 오버를 표시하는 위치에 사용됩니다.

$(".pop").each(function () {
        var $pElem = $(this);
        $pElem.popover(
            {
                html: true,
                trigger: "manual",
                title: getPopoverTitle($pElem.attr("id")),
                content: getPopoverContent($pElem.attr("id")),
                container: 'body',
                animation:false
            }
        );
    }).on("mouseenter", function () {
        var _this = this;
        $(this).popover("show");
        console.log("mouse entered");
        $(".popover").on("mouseleave", function () {
            $(_this).popover('hide');
        });
    }).on("mouseleave", function () {
        var _this = this;
        setTimeout(function () {
            if (!$(".popover:hover").length) {
                $(_this).popover("hide");
            }
        }, 100);
    });
    function getPopoverTitle(target) {
        return $("#" + target + "_content > h3.popover-title").html();
    };

    function getPopoverContent(target) {
        return $("#" + target + "_content > div.popover-content").html();
    };

팝 오버가 대상 요소의 자식이 아닌 경우에도 작동합니다. +1
Taha Paksu 2015 년

6

다음은 모든 팝 오버를 켜기 위해 일반 부트 스트랩 구현을 사용할 수 있도록 허용하면서 잘 작동하는 것처럼 보이는 솔루션입니다.

원래 바이올린 : https://jsfiddle.net/eXpressive/hfear592/

이 질문에 이식 :

<a href="#" id="example" class="btn btn-danger" rel="popover" >hover for popover</a>

$('#example').popover({
    html : true,
    trigger : 'hover',
    content : function() {
        return '<div class="box"></div>';
    }
}).on('hide.bs.popover', function () {
    if ($(".popover:hover").length) {
      return false;
    }                
}); 

$('body').on('mouseleave', '.popover', function(){
    $('.popover').popover('hide');
});

2

나는 가장 좋은 방법은 David Chase , Cu Ly 및 다른 사람들이 제공 한 것을 사용하는 것임을 동의합니다. 이를 수행하는 가장 간단한 방법 container: $(this)은 다음과 같이 속성 을 사용하는 것입니다.

$(selectorString).each(
  var $this = $(this);
  $this.popover({
    html: true,
    placement: "top",
    container: $this,
    trigger: "hover",
    title: "Popover",
    content: "Hey, you hovered on element"
  });
);

여기서는이 경우 팝 오버가 현재 요소의 모든 속성을 상속한다는 점을 지적하고 싶습니다 . 예를 들어 .btn요소 (부트 스트랩)에 대해이 작업을 수행 하면 popover 내부의 텍스트를 선택할 수 없습니다 . 나는 이것에 내 머리를 두드리는 데 꽤 많은 시간을 보냈기 때문에 그것을 기록하고 싶었습니다.


1

Vikas 답변은 저에게 완벽하게 작동하며 여기에서 지연 (표시 / 숨기기)에 대한 지원도 추가합니다.

var popover = $('#example');
var options = {
    animation : true,
    html: true,
    trigger: 'manual',
    placement: 'right',
    delay: {show: 500, hide: 100}
};   
popover
    .popover(options)
    .on("mouseenter", function () {

        var t = this;
        var popover = $(this);    
        setTimeout(function () {

            if (popover.is(":hover")) {

                popover.popover("show");
                popover.siblings(".popover").on("mouseleave", function () {
                    $(t).popover('hide');
                });
            }
        }, options.delay.show);
    })
    .on("mouseleave", function () {
        var t = this;
        var popover = $(this);

        setTimeout(function () {
            if (popover.siblings(".popover").length && !popover.siblings(".popover").is(":hover")) {
                $(t).popover("hide")
            }
        }, options.delay.hide);
    });     

또한 내가 변경 한 것에 주목하십시오.

if (!$(".popover:hover").length) {

와:

if (popover.siblings(".popover").length && !popover.siblings(".popover").is(":hover")) {

그래서 그것은 다른 어떤 팝 오버가 아닌 그 열린 팝 오버에서 정확히 참조하도록합니다 (이제 지연을 통해 동시에 하나 이상의 팝 오버를 열 수 있습니다).


마지막에 내가 한 코멘트는 container : body를 사용할 때 실제로 옳지 않습니다. 만약 그렇게 한 줄에 Vikas '솔루션을 사용해야한다면
user1993198

1

선택한 대답 은 작동 하지만 팝 오버가 body컨테이너로 초기화되면 실패합니다 .

$('a').popover({ container: 'body' });

선택한 답변을 기반으로 한 솔루션은 팝 오버를 사용하기 전에 배치해야하는 다음 코드입니다.

var originalLeave = $.fn.popover.Constructor.prototype.leave;
$.fn.popover.Constructor.prototype.leave = function(obj) {
    var self = obj instanceof this.constructor ? obj : $(obj.currentTarget)[this.type](this.getDelegateOptions()).data('bs.' + this.type);
    originalLeave.call(this, obj);

    if (obj.currentTarget) {
        self.$tip.one('mouseenter', function() {
            clearTimeout(self.timeout);
            self.$tip.one('mouseleave', function() {
                $.fn.popover.Constructor.prototype.leave.call(self, self);
            });
        })
    }
};

self.$tip팝 오버가 항상 요소의 형제가 될 것으로 예상하는 DOM을 순회하는 대신 변경 사항이 최소화 됩니다.


0

툴팁도 마찬가지입니다.

나를 위해 다음 솔루션은 모든 'mouseenter'에 이벤트 리스너를 추가하지 않기 때문에 작동하며 툴팁을 유지하는 툴팁 요소 위로 마우스를 가져갈 수 있습니다.

$ ->

  $('.element').tooltip({
    html: true,
    trigger: 'manual'
  }).
  on 'mouseenter', ->
    clearTimeout window.tooltipTimeout
    $(this).tooltip('show') unless $('.tooltip:visible').length > 0
  .
  on 'mouseleave', ->
    _this = this
    window.tooltipTimeout = setTimeout ->
      $(_this).tooltip('hide')
    , 100

$(document).on 'mouseenter', '.tooltip', ->
  clearTimeout window.tooltipTimeout

$(document).on 'mouseleave', '.tooltip', ->
  trigger = $($(this).siblings('.element')[0])
  window.tooltipTimeout = setTimeout ->
    trigger.tooltip('hide')
  , 100

0

이 솔루션은 나를 위해 잘 작동했습니다. (이제 방탄) ;-)

function enableThumbPopover() {
    var counter;

    $('.thumbcontainer').popover({
        trigger: 'manual',
        animation: false,
        html: true,
        title: function () {
            return $(this).parent().find('.thumbPopover > .title').html();
        },
        content: function () {
            return $(this).parent().find('.thumbPopover > .body').html();
        },
        container: 'body',
        placement: 'auto'
    }).on("mouseenter",function () {
        var _this = this; // thumbcontainer

        console.log('thumbcontainer mouseenter')
        // clear the counter
        clearTimeout(counter);
        // Close all other Popovers
        $('.thumbcontainer').not(_this).popover('hide');

        // start new timeout to show popover
        counter = setTimeout(function(){
            if($(_this).is(':hover'))
            {
                $(_this).popover("show");
            }
            $(".popover").on("mouseleave", function () {
                $('.thumbcontainer').popover('hide');
            });
        }, 400);

    }).on("mouseleave", function () {
        var _this = this;

        setTimeout(function () {
            if (!$(".popover:hover").length) {
                if(!$(this).is(':hover'))
                {
                    $(_this).popover('hide');
                }
            }
        }, 200);
    });
}

0
        $(function() {
            $("[data-toggle = 'popover']").popover({
                placement: 'left',
                html: true,
                trigger: "  focus",
            }).on("mouseenter", function() {
                var _this = this;
                $(this).popover("show");
                $(this).siblings(".popover").on("mouseleave", function() {
                    $(_this).popover('hide');
                });
            }).on("mouseleave", function() {
                var _this = this;
                setTimeout(function() {
                    if (!$(".popover:hover").length) {
                        $(_this).popover("hide")
                    }
                }, 100);
            });
        }); 

0

mouseleave창 초점이 갑자기 변경되는 것과 같은 이상한 일이 발생 하면 will이 실행되지 않고 사용자가 브라우저로 돌아옵니다. 그런 경우 mouseleave커서가 요소를 다시 떠날 때까지 실행되지 않습니다.

이 솔루션 mouseenterwindow개체 에 의존 하므로 마우스를 페이지의 다른 곳 으로 이동하면 사라집니다 .

이는 페이지에서이를 트리거 할 여러 요소 (예 : 테이블)를 사용하도록 설계되었습니다.

var allMenus = $(".menus");
allMenus.popover({
    html: true,
    trigger: "manual",
    placement: "bottom",
    content: $("#menuContent")[0].outerHTML
}).on("mouseenter", (e) => {
    allMenus.not(e.target).popover("hide");
    $(e.target).popover("show");
    e.stopPropagation();
}).on("shown.bs.popover", () => {
    $(window).on("mouseenter.hidepopover", (e) => {
        if ($(e.target).parents(".popover").length === 0) {
            allMenus.popover("hide");
            $(window).off("mouseenter.hidepopover");
        }
    });
});

0

다음 과 같이 더 유연 해질 것 입니다 hover().

$(".my-popover").hover(
    function() {  // mouse in event
        $this = $(this);
        $this.popover({
            html: true,
            content: "Your content",
            trigger: "manual",
            animation: false
            });
        $this.popover("show");
        $(".popover").on("mouseleave", function() {
            $this.popover("hide");
        });
    },
    function() {  // mouse out event
        setTimeout(function() {
            if (!$(".popover:hover").length) {
                $this.popover("hide");
            }
        }, 100);
    } 
)

0

간단하다 :)

$('[data-toggle="popover"]').popover( { "container":"body", "trigger":"focus", "html":true });
$('[data-toggle="popover"]').mouseenter(function(){
    $(this).trigger('focus');
});

0

나는 최근에 KO로 작업해야했고 위의 솔루션은 표시 및 숨기기가 지연 될 때 잘 작동하지 않았습니다. 아래에서이 문제를 해결해야합니다. 부트 스트랩 도구 설명이 작동하는 방식을 기반으로합니다. 이것이 누군가를 돕기를 바랍니다.

var options = {
                delay: { show: 1000, hide: 50 },
                trigger: 'manual',                      
                html: true
            };
var $popover = $(element).popover(options);

$popover.on('mouseenter', function () { // This is entering the triggering element
    var self = this;

    clearTimeout(self.timeout);
    self.hoverState = 'in';

    self.timeout = setTimeout(function () {
        if (self.hoverState == 'in') {
            $(self).popover("show");

            $(".popover, .popover *").on('mouseover', function () { // This is moving over the popover
                clearTimeout(self.timeout);
            });                                                                 

            $(".popover").on('mouseleave', function () { // This is leaving the popover
                self.timeout = setTimeout(function () {
                    if (self.hoverState == 'out') {
                        $(self).popover('hide');
                    }
                }, options.delay.hide);
            });
        }
    }, options.delay.show);
}).on('mouseleave', function (event) { // This is leaving the triggering element
    var self = this;

    clearTimeout(self.timeout);
    self.hoverState = 'out';

    self.timeout = setTimeout(function () {                             
        if (self.hoverState == 'out') {
            $(self).popover('hide');
        }

    }, options.delay.hide);
});

-1

이것은 지연 및 ajax에 의해로드 된 쇼 다이내믹 툴팁에 대한 내 코드입니다.

$(window).on('load', function () {
    generatePopovers();
    
    $.fn.dataTable.tables({ visible: true, api: true }).on('draw.dt', function () {
        generatePopovers();
    });
});

$(document).ajaxStop(function () {
    generatePopovers();
});

function generatePopovers() {
var popover = $('a[href*="../Something.aspx"]'); //locate the elements to popover

popover.each(function (index) {
    var poplink = $(this);
    if (poplink.attr("data-toggle") == null) {
        console.log("RENDER POPOVER: " + poplink.attr('href'));
        poplink.attr("data-toggle", "popover");
        poplink.attr("data-html", "true");
        poplink.attr("data-placement", "top");
        poplink.attr("data-content", "Loading...");
        poplink.popover({
            animation: false,
            html: true,
            trigger: 'manual',
            container: 'body',
            placement: 'top'
        }).on("mouseenter", function () {
            var thispoplink = poplink;
            setTimeout(function () {
                if (thispoplink.is(":hover")) {
                    thispoplink.popover("show");
                    loadDynamicData(thispoplink); //load data by ajax if you want
                    $('body .popover').on("mouseleave", function () {
                        thispoplink.popover('hide');
                    });
                }
            }, 1000);
        }).on("mouseleave", function () {
            var thispoplink = poplink;
            setTimeout(function () {
                if (!$("body").find(".popover:hover").length) {
                    thispoplink.popover("hide");
                }
            }, 100);
        });
    }
});

function loadDynamicData(popover) {
    var params = new Object();
    params.somedata = popover.attr("href").split("somedata=")[1]; //obtain a parameter to send
    params = JSON.stringify(params);
    //check if the content is not seted
    if (popover.attr("data-content") == "Loading...") {
        $.ajax({
            type: "POST",
            url: "../Default.aspx/ObtainData",
            data: params,
            contentType: "application/json; charset=utf-8",
            dataType: 'json',
            success: function (data) {
                console.log(JSON.parse(data.d));
                var dato = JSON.parse(data.d);
                if (dato != null) {
                    popover.attr("data-content",dato.something); // here you can set the data returned
                    if (popover.is(":hover")) {
                        popover.popover("show"); //use this for reload the view
                    }
                }
            },

            failure: function (data) {
                itShowError("- Error AJAX.<br>");
            }
        });
    }
}

당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.