Nice programing

하나의 팝 오버를 표시하고 다른 팝 오버를 숨 깁니다.

nicepro 2020. 12. 9. 21:44
반응형

하나의 팝 오버를 표시하고 다른 팝 오버를 숨 깁니다.


버튼이 여러 개 있고 각각에 대해 팝 오버가 필요합니다.
나는 이것을 원한다 :
내 사용자가 그들 중 하나를 클릭하면 다른 사람들이 숨겨지기를 원합니다. 따라서 하나의 팝 오버 만 표시되며이
예제 plz를 수정하는 데 도움이됩니다.

var mycontent='<div class="btn-group"> <button class="btn">Left</button> <button class="btn">Middle</button> <button class="btn">Right</button> </div>'
$('.btn').popover({
    html: true,
    content:mycontent,
    trigger: 'manual'
}).click(function(e) {
    $(this).popover('toggle');
    e.stopPropagation();
});

$('html').click(function(e) {
     $('.btn').popover('hide');
});

내 HTML :

<ul>
    <li>
        <a href="#" class="btn" data-toggle="popover" data-placement="bottom" title="" >Popover</a>
    </li>
    <li>
       <a href="#" class="btn" data-toggle="popover" data-placement="bottom" title="" >Popover</a> 
    </li>
</ul>

jsfiddle 예

아래 코드와 같은 것을 추가하면 어떻게 든 내 문제가 해결되었습니다.

$('.btn').click(function(e) {
     $('.btn').popover('hide');
});

하지만 각 버튼을 두 번 클릭하면 잘못됩니다


어떻게 든 내 필요에 대한 하나의 예를 만들었습니다. 이 코드를 사용했습니다.

$('.btn').popover();

$('.btn').on('click', function (e) {
    $('.btn').not(this).popover('hide');
});

여기 에서 데모를 확인 하세요

이전 수정 데모 내가 그것을 다른 사람을 도움이 될 것입니다 희망을


이전에 본 답변에는 동적 팝 오버가 없었기 때문에 이것이 제가 생각 해낸 것입니다. 일부가 지적했듯이 팝 오버를 사용하여 DOM에서 제거하지 않으면 문제를 일으키는 문제가 .remove()있습니다. 부트 스트랩 웹 사이트에서 예제포크 하고이 새로운 바이올린을 만들었습니다 . selector: '[rel=popover]'옵션을 사용하여 동적 팝 오버가 추가됩니다 . 팝 오버가 표시 되려고 할 때 다른 모든 팝 오버에 대해 destroy를 호출 한 다음 .popover페이지 에서 콘텐츠 를 제거합니다 .

$('body').popover({
                selector: '[rel=popover]',
                trigger: "click"
            }).on("show.bs.popover", function(e){
                // hide all other popovers
                $("[rel=popover]").not(e.target).popover("destroy");
                $(".popover").remove();                    
            });

가장 쉬운 방법은 trigger="focus"팝 오버 를 설정 하는 것입니다.

다음 클릭시 해제

사용자가 다음에 클릭 할 때 팝 오버를 닫으려면 포커스 트리거를 사용합니다.

<a tabindex="0" class="btn btn-lg btn-danger" role="button" data-toggle="popover" data-trigger="focus" title="Dismissible popover" data-content="And here's some amazing content. It's very engaging. Right?">Dismissible popover</a>

참고 -클릭하면 팝 오버가 숨겨집니다.


이것은 팝 오버의 클래스가 무엇인지 미리 알 필요가없는 곳에서 사용하는 빠른 일반 솔루션입니다. 나는 그것을 매우 광범위하게 테스트하지 않았습니다. 또한 숨기기가 토글과 완전히 다르게 작동하는 데 몇 가지 문제가 있었기 때문에 아래 토글을 사용하고 있습니다.

  var $currentPopover = null;
  $(document).on('shown.bs.popover', function (ev) {
    var $target = $(ev.target);
    if ($currentPopover && ($currentPopover.get(0) != $target.get(0))) {
      $currentPopover.popover('toggle');
    }
    $currentPopover = $target;
  });

  $(document).on('hidden.bs.popover', function (ev) {
    var $target = $(ev.target);
    if ($currentPopover && ($currentPopover.get(0) == $target.get(0))) {
      $currentPopover = null;
    }
  });

Bootstrap 3.3.7을 사용하여이 솔루션을 찾습니다.

var _popoverLink = $('[data-toggle="popover"]');

_popoverLink.on('click', function(){
  _popoverLink.popover('destroy').popover({container: 'body'});
  $(this).popover('show');
});

문안 인사.


당신은 이것을 너무 심각하게 받아들이고 있습니다. 새로운 팝 오버를 열기 전에 모든 열린 팝 오버를 닫으십시오 :

// Hide any active popover first
            $(".popover").each(function () {
                var $this = $(this);
                $this.popover('hide');
            });

//Now Execute your new popover
$('.btn').popover({
                html: true,
                content: mycontent,
                trigger: 'manual'
            }).click(function (e) {
                $(this).popover('toggle');
                e.stopPropagation();
            });

나를 위해 일한 솔루션이 있습니다. 내 스크립트에서는 HTML의 데이터 속성을 통해 vars를 전달하지 않고 js 파일의 논리를 선호합니다.

            $(".vote").popover({
                trigger: " click",
                title: "Attention",
                content: "You must be a member of the site to vote on answers.",
                placement: 'right'
            });

            $('.vote').on('click', function (e) {
                $('.vote').not(this).popover('hide');
            });

부트 스트랩 v3을 사용 하여이 문제를 해결하기 위해 게시 된 답변을 사용하는 데 어려움이있었습니다. 몇 가지 검색 후 내 주요 문제가 적절한 팝 오버 트리거를 설정하지 않는 것을 발견했습니다. op의 질문에 나열된대로 'manual'로 설정되어야합니다.

다음 단계는 매우 간단하고 다른 답변에서 보는 솔루션보다 더 나은 동작을 제공하므로 공유 할 것이라고 생각했습니다.

$('html').on('click', function(e) {
  if($(e.target).hasClass('btn')) {
    $(e.target).popover('toggle');
  }

  if(!$(e.target).parent().hasClass('popover')) {
    $('.popover').prev('.btn').not(e.target).popover('toggle');
  }
});

이 솔루션은 다른 팝 오버 링크를 포함하여 페이지의 다른 곳을 클릭 할 때 팝 오버를 닫을 수있는 기능을 제공하지만 팝업을 닫지 않고 팝 오버 자체를 클릭하여 텍스트 복사와 같은 작업을 위해 사용자가 팝 오버에 액세스 할 수 있도록합니다.

이것이 누군가에게 도움이되기를 바랍니다. 여기에 작동하는 바이올린이 있습니다. https://jsfiddle.net/hL0pvaty/

p.s. - I am only using the .btn class as the selector in my example because it is used in the op's question. I would recommend using something less generic.


I went for a combinations of approaches I've seen both on this thread and others. My requirements specify that:

  • Only one popover should be visible at a time
  • A click anywhere outside the popover should dismiss the popover
  • The popover should contain a control
  • Should not require rebinding the popover event

        function bindEvents() {
    
             setupPopupBinding();
    
             setupPopupDismissal();
        };
    
        function setupPopupBinding() {
               $('.addSectionItem').popover({
                      html: true,
                      content: function () {
                            return createDropdowns($(this).data('sectionid'))[0].outerHTML;
                      },
                      placement: "right",
                      trigger: "click focus"
               }).on("inserted.bs.popover", function (e) {
                    //initialize dropdown
                    setupSelect2();
               }).on("hide.bs.popover", function (e) {
                     $('.select2-container--open').remove();
               });
        }
    
        function setupPopupDismissal() {
               $('body:not(.addSectionItem)').on('click', function (e) {
               $('.addSectionItem').each(function () {
               //the 'is' for buttons that trigger popups
               //the 'has' for icons within a button that triggers a popup
               if (!$(this).is(e.target) && $(this).has(e.target).length === 0 && $('.popover').has(e.target).length === 0) {
               $(this).popover('hide');
               $('.popover').has(e.target).remove();
            }
        });
        });
        }
    
        function createDropdowns(sectionId: number) {
               var dropdown = $('<div/>')
               .attr('Id', 'sectionPopupWrapper' + sectionId)
               .addClass('popupWrapper')
               .append($('<select/>').addClass('sectionPopup'))
               .append($('<button/>').addClass('btn btn-primary btn-xs')
               .attr('data-sectionid', sectionId)
               .text('Add'));
    
        return dropdown;
        }
    

<ul>
<li><i class="fa fa-trash-o DeleteRow" id=""></i>1</li>
<li><i class="fa fa-trash-o DeleteRow" id=""></i>2</li>
<li><i class="fa fa-trash-o DeleteRow" id=""></i>3</li>
</ul>

// Close other popover when click on Delete/Open new popover - START //
     $('.DeleteRow').on('click', function (e) {
        $('.popover').not(this).popover('hide');
     });
 // Close other popover when click on Delete/Open new popover - END//

With the help of "losmescaleros" answer, this works perfectly for me :

$('body').popover({
  selector: '[data-toggle="popover"]',
  trigger: "click"
}).on("show.bs.popover", function(e){
  // hide all other popovers
  $("[data-toggle='popover']").not(e.target).popover("destroy");                  
});

Without any double click issues.


This is the simplest and elegant way to do this:

    $('[data-toggle="popover"]').on('click', function(){
        $('[data-toggle="popover"]').not(this).popover('hide');
    });

When an icon is clicked and has open the corresponding popover then it has a value that begins with "popover*" called aria-describedby.

So you find this icons and trigger click on them but not on the icon which is clicked now.

$('.icon-info').click(function(){
    $(".icon-info[aria-describedby*='popover']").not(this).trigger('click');
});

참고URL : https://stackoverflow.com/questions/16150163/show-one-popover-and-hide-other-popovers

반응형