How to center the Bootstrap Tooltip on an SVG?

2019-03-15 19:39发布

I want to shift the tooltip a few pixels to the right, so the arrow is in the center of the cell where the cursor is (currently, it's positioned at (0,0), that is, top left). This is my code:

 $("rect.cell").tooltip({
    title: "hola",
    placement: "top"
  });

and an image: enter image description here

Ideally I'd like to do this using javascript, so I can update the number of pixels if I change the size of the cells.

3条回答
\"骚年 ilove
2楼-- · 2019-03-15 20:13

It appears to be a bug in Firefox/Chrome for SVG elements (as is my case) https://bugzilla.mozilla.org/show_bug.cgi?id=649285

so I just changed the bootstrap-tooltip.js from this:

getPosition: function (inside) {
  return $.extend({}, (inside ? {top: 0, left: 0} : this.$element.offset()), {
    width: this.$element[0].offsetWidth
  , height: this.$element[0].offsetHeight
  })
}

to this:

getPosition: function (inside) {
  return $.extend({}, (inside ? {top: 0, left: 0} : this.$element.offset()), {
    width: this.$element[0].getBBox().width
  , height: this.$element[0].getBBox().height
  })
}
查看更多
仙女界的扛把子
3楼-- · 2019-03-15 20:19

Here's a simple extension of nachocab's getPosition implementation that supports both regular HTML elements and SVG elements:

getPosition: function (inside) {
  var el = this.$element[0]
  var width, height

  if ('http://www.w3.org/2000/svg' === el.namespaceURI) {
      var bbox = el.getBBox()
      width = bbox.width
      height = bbox.height
  } else {
      width = el.offsetWidth
      height = el.offsetHeight
  }

  return $.extend({}, (inside ? {top: 0, left: 0} : this.$element.offset()), {
    'width': width
  , 'height': height
  })
}
查看更多
Ridiculous、
4楼-- · 2019-03-15 20:22

I found that positioning was wonky in Chrome (proper height, but positioned at the far left of the svg:rect element) and Firefox (proper height, totally incorrect x position). I'd been using the svgdom plugin for jQuery (unsure if that threw off my results at all), but here's the solution that I came up with:

https://gist.github.com/2886616

It's a diff against a combined boostrap.js. Here's the long dormant issue that someone else filed against bootstrap:

https://github.com/twitter/bootstrap/issues/2703

查看更多
登录 后发表回答