简体   繁体   中英

Bootstrap popover position and placement and tip

How do you position the bootstrap popover so that it doesn't float away from the triggering element upon window resize?

what css needs to be applied to move the tip to the top edge of the popover ie near the corner?

I have the following options set but it places the popover on the left instead of right.

$(function () {
  $('.js-tooltip-trigger').popover({
    html: true,
    trigger: 'focus',
    placement: 'auto right',
    content: function (e) {
        return $(this).parent(".form-group").find(".js-tooltip").html();
    }
  }).on('shown.bs.popover', function () {
       $('.popover').css('top',parseInt($('.popover').css('top')) + 22 + 'px')
     });
});  

The html:

<div class="form-group">
<label for="ref">Reference</label>

<input type="text" class="form-control js-tooltip-trigger" id="ref" maxlength="50" >  

<div class="js-tooltip" style="display: none;">
    <p><strong>Your reference is optional.</strong></p>
    <p>Enter a code of your choice for reference purposes.</p>
</div>
</div>

I'm not a fan of how this works, but essentially you have to create an element that stays in the position you want the popover , and append the popover to it. In this case, I have used the container you already have in place for the tooltip html. I'm creating container ID's dynamically so you don't have to worry about doing that in your html.

So for this HTML:

<div class="form-group pos-relative">
    <label for="ref">Reference</label>
    <input type="text" class="form-control js-tooltip-trigger" id="ref" maxlength="50">
    <span class="js-tooltip" style="display: none;">
        <p><strong>Your reference is optional.</strong></p>
        <p>Enter a code of your choice for reference purposes.</p>
    </span>
</div>

This CSS:

.pos-relative{
  position:relative;
}
.js-tooltip{
   position:absolute; 
   top:0;
   right:0;
}

And this JS--here's where it happens:

$(function () {

  $('.js-tooltip-trigger').each(function(ind, ele){

    var $ele = $(ele),
        $ttSpan = $ele.next('.js-tooltip'),
        ttHtml = $ttSpan.html(),
        rndID = 'ttid'+ String(Math.random()).substr(2);

    // set the ID, strip the style, and empty the html--
    // we already have it stored in the var above
    $ttSpan.attr('id', rndID).removeAttr('style').html('');

    // make the popovers
    $ele.popover({
        html: true,
        trigger: 'focus',
        placement: 'right',
        container: '#'+rndID, 
        content: ttHtml
    });

  });

});

See it in action here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM