programing

부트스트랩의 '팝오버' 컨테이너에 클래스를 동적으로 추가

telebox 2023. 9. 14. 22:29
반응형

부트스트랩의 '팝오버' 컨테이너에 클래스를 동적으로 추가

나는 a를 사용하고 싶습니다.data-소예:data-class 탑 나는 더 요!)를 d!<div> 현재 가지고 있는 코드는 다음과 같습니다.

jQuery:

$('a[rel=popover]')
    .popover({
        placement : 'bottom',
        trigger : 'hover'
    })
    .click(function(e) {
        e.preventDefault()
    });

HTML:

<a href="" rel="popover" data-class="dynamic-class" title="Title goes here" data-content="Content goes here">

그리고 이상적으로 제가 뱉어냈을 HTML의 종류는 다음과 같습니다.

<div class="popover ... dynamic-class">
    <!-- remainder of the popover code as per usual -->
</div>

이게 제가 할 수 있는 일인가요?

팝오버용 부트스트랩 사이트의 문서가 조금 희박해서, 아쉽게도 이 지점까지 도달하는 데 시간이 좀 걸렸습니다.

부트스트랩을 해킹하지 않고 템플릿을 변경하지 않고 호출자의 오브젝트에서 팝업 오브젝트를 잡아냄으로써 이 작업을 수행할 수 있습니다.data 그것의하는에 하는 것.$tip소유물.

$('a[rel=popover]')
  .popover({ placement: 'bottom', trigger: 'hover' })
  .data('bs.popover')
  .tip()
  .addClass('my-super-popover');

버전 2.3에서는 이 작업을 수행하는 또 다른 방법이 있습니다.컨테이너에 클래스를 포함하도록 기본 템플릿을 재정의합니다.

var pop = $('a', this.el).popover({
  trigger: 'click'
  , template: '<div class="popover awesome-popover-class"><div class="arrow"></div><div class="popover-inner"><h3 class="popover-title"></h3><div class="popover-content"><p></p></div></div></div>'
});

@bchhun이 쓴 글과 많은 머리 긁기를 바탕으로, 저는 그것이 효과가 있기 때문에, 제 자신의 질문에 대답해야 한다고 느꼈습니다.저 또한 이것이 호감을 받고 좋아했다는 것을 알았기 때문에 저와 같은 jQuery의 신입인 다른 사람을 돕고 싶습니다.

현재 부트스트랩 빌드 [v2.1.0]에서는 스크립트가 모두 통합됩니다.줄을 경우를 제거한 경우), 합니다..js파일입니다. 다음과 같은 코드가 있습니다.

$tip
  .css(tp)
  .addClass(placement)
  .addClass('in')

여기에 새 줄을 추가하게 됩니다.

  .addClass(this.$element.attr("data-class"))

그래서 이제 당신이 추가할 때마다data-class업에을다합니다.<div class="popover">

이제 보니 너무 뻔하네요 :)

오래된 게시물이지만 참고로 추가합니다.상위 클래스에 동적 클래스를 추가하는 대신 Shankar Cabus 답변을 수정하면 생성된 .popover div에 추가됩니다.

$(function(){
    $('a[rel=popover]')
    .popover({
        placement : 'bottom',
        trigger : 'hover'
    })
    .on("hover", function(){
        $('.popover').addClass($(this).data("class")); //Add class .dynamic-class to <div>
    });
});

도움이 되길 바라요 :)

다른 사람을 대상으로 하지 않고 적절한 팝업에만 해당 클래스를 추가하는 것은 어떨까요?

$('#someElement').popover({placement: function(context, src) {
    $(context).addClass('my-custom-class');
    return 'top'; // - 'top' placement in my case
});

또는 'someElement'의 데이터에서 사용자 정의 클래스 이름을 가져오는 것과 같은 일부 변형:

$('#someElement').popover({placement: function(context, src) {
    $(context).addClass($(src).data('customClassName'));
    return 'top';
});

툴팁 초기화 시 숨겨진 "템플릿" 옵션만 설정하면 됩니다.왜 부트스트랩 팀이 이 일을 비밀에 부치는지...

$(elem).popover({
    template: '<div class="popover YOURCLASS"><div class="arrow"></div><h3 class="popover-title"></h3><div class="popover-content"></div></div>'
}).popover('show');

이게 도움이 되길...

이것은 몇 년 전에 물은 적이 있고, 많은 답이 있습니다.하지만..저는 최근에 같은 문제를 직접 해결해야 했고, 저는 - (a) 소스 코드를 조작하는 것을 피하고 싶었고 (b) 지속적으로 재사용하기 위해 일반적인 솔루션이 필요했습니다 (그래서)template: '...'각 초기화에 대한 솔루션이 아웃(out)되었습니다.

제 해결책은 충분히 간단했고, 표시된 답변과 약간 같습니다. 저는 팝오버가 확장이라고 생각했습니다.tooltip.js도서관.제 말은 -- 확인해 보세요, 소스코드가 100줄이 조금 넘습니다.그래서 나는 다음과 같은 파일을 만들었습니다.popover-extend.js하여 붙여넣었습니다. 해서 해서 여기서부터는 다음과 같은 선을 쉽게 조작할 수 있었습니다.

Popover.DEFAULTS = $.extend({}, $.fn.tooltip.Constructor.DEFAULTS, {
    // add this:
    cls: ''
});

다음:

Popover.prototype.setContent = function () {
    // add this:
    if (this.options.cls) {
        $tip.addClass(this.options.cls);    
    }

이제 다음을 수행할 수 있습니다.

<a href="#" rel="popover" 
   data-cls="dynamic-class" 
   title="Title goes here" data-content="Content goes here">

저와 비슷하고 더 많은 기능을 추가하고 싶다면 정말 좋은 접근 방식입니다.예를 들어 제목에 일반 닫기 단추를 추가한 방법은 다음과 같습니다(팝오버에 지정된 ID가 있어야 함).

// added this to the the DEFAULTS
close: ''


// added this to the setContent function
if (this.options.close) {
    var id = this.$element.attr('id'),
        btn = $("<button></button>", {
            "class": "close",
            "id": "close",
            "onclick": "$('#"+id+"').popover('hide');"
    }),

    title = $tip.find('.popover-title');

    btn.html("&times;");
    btn.appendTo(title);
}

html을 할 수 입니다. DUFAULT라는 이름의 하면 html을 통해 설정할 수 있습니다. 예를 들어, 이름을 가진 변수를 추가할 수 있습니다.foo를 으로 할 입니다 입니다 을 통해 자동으로 조작할 수 있습니다.data-foo=.

이것이 소스 코드를 조작하는 대안을 찾는 사람들에게 도움이 되기를 바랍니다.

저도 같은 문제가 있었습니다. @Kate의 답변이 마음에 들었습니다. 하지만 소스 파일의 변경은 앞으로 너무 많은 문제를 일으킬 수 있기 때문에 부트스트랩의 버전을 업데이트할 때 이러한 작은 변경 사항을 잊어버릴 수 있습니다.그래서 저는 다른 방법을 찾았습니다.

 $(element).popover({...}).data("popover").tip().addClass("your_class")

처럼 @CorayThan으로 합니다.data("popover")

popover의 method tip()는 popover 요소를 반환하고, popover 요소가 생성되지 않을 때 생성하므로, 비록 당신이 popover의 초기화에 있더라도 항상 정확한 popover 요소를 얻을 수 있을 것입니다(이것이 나의 경우 =D입니다.

여기는 시간이 늦어지고 피곤하지만 부트스트랩의 js 파일을 업데이트하기로 결정하면 앞으로 작동하지 않는 빠른 원라이너가 있습니다.

150번 행의 이 요지에서 bootstrap-tooltip.js 파일을 살펴봅니다.

여기 수정된 툴팁이 있습니다.

Here's the modified tooltip in action

아래 검사기 창을 확인하면 동적 클래스가 툴팁에 추가된 것을 확인할 수 있습니다.

좀 더 장기적이고 적절한 답변을 내일 올리겠습니다.

저는 이 정도면 돼요.여기 '이벤트' 섹션의 부트스트랩 설명서에서 영감을 얻었습니다.

$("a[rel=popover]").popover().on("show.bs.popover", function(){
    $(".popover").addClass("your-custom-class");
});

또한 'template' 옵션을 사용할 수 있습니다.

$element.popover({                               
   html: true,
   trigger: 'click',
   template: '<div class="popover '+MY_CLASS+'" role="tooltip"><div class="arrow"></div><h3 class="popover-title"></h3><div class="popover-content"></div></div>',
   content: function() {
    return 'hello';
   }
});

데이터 클래스 속성에서 MY_CLASS를 업데이트합니다.

당신은 사용할 수 있습니다.container이 문제를 해결할 수 있는 옵션이 있습니다.

$('[data-toggle="popover"]').popover({
    container: '#foo'
});

태그 속성을 통해 설정할 수도 있습니다.

<a href="#" data-toggle="popover" data-container="#foo" data-content="Content">Foo</a>

그리고 바디 태그를 닫기 전에 이것을 어딘가에 추가합니다.

<div id="foo"></div>

그러면 당신이 할 수 있는 일은#foo > .popover에 딱 것을 알고 입니다. 이것이 천편일률적인 해결책이 아니라는 것을 알고 있지만, 그것이 하나의 방법입니다.

이 스레드가 오래된 것은 알지만, 제가 그랬던 것처럼 이 기사를 우연히 발견한 사람들을 위해, 여기에 더 많은 커스터마이징을 허용하는 다른 방법이 있습니다.부트스트랩 4로 테스트를 해본 적은 없지만 부트스트랩 3으로 테스트를 해봤습니다.

함수의 클래스를 하드 코딩하는 대신 사용자 지정 데이터 속성을 사용하여 html 요소를 통해 cs 클래스를 팝업에 '제출'할 수 있습니다.이 예를 들어 저는 그 속성을 "데이터 클래스"라고 불렀습니다.

이 방법은 팝오버 'placement' 옵션에서 사용할 수 있는 기능을 이용하기 때문에, 저는 팝오버에서 구성된 원래의 배치를 유지하도록 구성했습니다.

jQuery( '[data-toggle="popover"]' ).popover({

    container: 'body',

    placement: function ( popover, trigger ){

        // Get the submitted placement for the popover
        var placement = jQuery( trigger ).attr( 'data-placement' );

        // Get the class(es) to apply to the popover
        var dataClass = jQuery( trigger ).attr( 'data-class' );

        // Apply the submitted class(es) to the popover element
        jQuery( popover).addClass( dataClass );

        // Return the original placement for the popover
        return placement;

        },

        trigger: 'hover'

});

도움이 되었으면 좋겠습니다.만약 누군가가 이것을 하는 더 좋은 혹은 더 깨끗한 방법을 가지고 있다면 기꺼이 배울 것입니다.

됩니다.bootstrap core class, 속성을 추가하기만 하면 됩니다.data-class나더더나를dnndataClass:당신에게 충실한tooltip

!function($){   
    $.extend($.fn.tooltip.Constructor.DEFAULTS,{
        dataClass: false
    }); 
    var Tooltip = $.fn.tooltip.Constructor;
        _show = Tooltip.prototype.show;

    Tooltip.prototype.show = function (){
        _show.apply(this,Array.prototype.slice.apply(arguments));

        if (this.options.dataClass!=="undefined" && this.options.dataClass){
            var that = this;
            var $tip = this.tip();
            if (this.$element.attr("data-class") !== undefined)
                $tip.addClass(this.$element.attr("data-class"));
        }
    };
}(jQuery);

bootstrap v3.3.2의 경우 bootstrap.js에서 이러한 행을 찾을 수 있습니다.

   $tip
    .detach()
    .css({ top: 0, left: 0, display: 'block' })
    .addClass(placement)
    .data('bs.' + this.type, this)

그다음에 이 선을 더하면 됩니다.

    .addClass(this.$element.attr("data-class")) 

요소에 를 하려면 을 해야 에 해야 을 하려면 를 에 data-class="classexemple"하게 작동합니다.

www.mixpres.com 에서 저희를 찾으세요.

에서는 4을 할 수 .data-template특성:

<button data-toggle="popover" data-template='<div class="popover MYSUPERCLASS" role="tooltip"><div class="popover-arrow"></div><h3 class="popover-title"></h3><div class="popover-content"></div></div>' data-offset="-10 0" data-html="true" data-trigger="focus" data-placement="bottom" data-content='My Popover'>Button</button>
$('a[rel=popover]')
  .popover({ placement: 'bottom', trigger: 'hover' })
  .data('bs.popover')
  .addAttachmentClass('my-own-popover')

알게 될 겁니다.bs-popover-my-own-popover 안의 .popover요소.

이 문제에 대한 가장 좋은 해결책은 팝오버를 확장하고 자신만의 버전의 팝오버를 구축하는 것입니다.아래는 코드이며 부트스트랩 버전 3.3.7을 기반으로 합니다.

        (function($){
            var PopoverEx = function(element, options){
                this.init('popover', element, options);
            }

                PopoverEx.prototype = $.extend({}, $.fn.popover.Constructor.prototype, {

                    constructor: PopoverEx,
                    tip: function(){
                        if(!this.$tip){
                            this.$tip = $(this.options.template);
                            if(this.options.modifier) this.$tip.addClass(this.options.modifier);
                        }
                        return this.$tip; 
                    }       
                });

            $.fn.popoverex = function(option){
               return this.each(function () {
                var $this   = $(this)
                var data    = $this.data('bs.popover')
                var options = typeof option == 'object' && option

                if (!data && /destroy|hide/.test(option)) return
                if (!data) $this.data('bs.popover', (data = new PopoverEx(this, options)))
                if (typeof option == 'string') data[option]()
              })
            }
        })(window.jQuery);

사용.

HTML 코드

    <a href="#" class="btn btn-large btn-danger" 
          rel="popover" 
          data-modifier="popover-info" 
          title="A Title" 
          data-content="And here's some amazing content.right?">Hover for popover</a>   

JS대본

    jQuery(document).ready(function($) {
        $('[rel="popover"]').popoverex();
    });

이 git 페이지 https://gist.github.com/vinoddC/475669d94e97f4d7b6bcfde4cef80420 에서 전체 버전과 설명을 찾을 수 있습니다.

브라이언 우드워드 작품의 최신 버전입니다.

미안하지만 당신의 질문을 잘 이해하지 못했습니다.하지만 당신이 원하는 것은 부모 디브를 추가하는 것입니까?진정하세요...원하는 것이 무엇인지 확인합니다.

$(function(){
    $('a[rel=popover]')
    .popover({
        placement : 'bottom',
        trigger : 'hover'
    })
    .on("click", function(){
        $(this).closest("div").addClass($(this).data("class")); //Add class .dynamic-class to <div>
    });
});

데모: http://jsfiddle.net/PRQfJ/

BS의 모든 버전에서 작동하는 최선의 선택은 특정 클래스 안에 만들고 그것을 보여준 후에 그 클래스를 찾아서 당신의 클래스 이름을 팝업 부모에 추가하는 것입니다.

// create a template that add the message inside
var $tmp = $("<div class='popoperrormessage'>" + error + "</div>");


            $(this).popover("destroy").popover({
                trigger: "manual",
                animation: false,
                html: true,
                placement:"right",
                content: $tmp,
                container: "body"
            }).popover("show");


            // now we have to find the parent of the popoperrormessagemessage
            $(".popoperrormessage").parents(".popover").addClass("hello");

이제 너의 poppover는 hello class를 할 것입니다.

여기에 제 해결책이 있습니다. 아마도 가장 효율적이지는 않지만 구현하기가 가장 쉽다는 것을 알게 되었습니다.

 $('[data-content]').each(function(){
    var options = {
        html: true //optional
    };

    if ($(this)[0].hasAttribute('data-class')) {
        options['template'] = '<div class="popover" role="tooltip ' + $(this).attr('data-class') + '"><div class="arrow"></div><h3 class="popover-title"></h3><div class="popover-content"></div></div>';
    }

    $(this).popover(options);
});

추가하기만 하면 됩니다.data-class="custom-class"다른 예들과 같은 요소로.

왜 그러시는지 모르겠지만, 제 예를 들어, 저는 그냥 맞춤 스타일을 설정하고 싶었어요.그래서 CSS에서 현재 popover. 즉, rating-popover - 이것은 popover를 열기 위한 나의 링크입니다. -> popover 요소는 그 요소의 다음에 생성됩니다. 그래서 우리는 그것을 선택할 수 있습니다.

a.rating-popover + div.popover{
   background: blue;
}

파란 배경에 보일라도 있고요a.rating-popover 요소로 열린 팝오버에만 적용됩니다.

언급URL : https://stackoverflow.com/questions/12170357/dynamically-add-a-class-to-bootstraps-popover-container

반응형