Tippy.js 不显示数据属性中的内容?

问题描述 投票:0回答:2

我已经安装了 tippy.js 来处理我的工具提示,但是我正在努力让工具提示显示数据属性中的内容集。我的默认工具提示工作正常,但是当我通过一个类初始化时,为了能够向工具提示添加不同的样式,它没有从工具提示中获取内容。

tippy.setDefaults({
    animation: 'scale',
    animateFill: false,
    maxWidth: 240,
    duration: 0,
    arrow: false,
})

tippy('.js-tippy-reviews', {
    theme: 'reviews',
    animation: 'scale',
    animateFill: false,
    maxWidth: 240,
    duration: 0,
    arrow: false,
})

如果我将 content 方法添加到 tippy 它将显示,但是由于工具提示的内容是动态的,我需要在数据属性上设置它。我不确定如何将数据属性从元素传递到 tippy。

content: this.dataset.tippy

知道我做错了什么吗?

HTML:

<div class="js-tippy-reviews reviews-notification" data-tippy="2 Pending Reviews"></div>
javascript tooltip tippyjs
2个回答
8
投票

您可以添加 onShow() 函数并从实例中读取它并从参考数据集中设置内容。

tippy.setDefaults({
      animation: 'scale',
      animateFill: false,
      maxWidth: 240,
      duration: 0,
      arrow: false,
  });

  tippy('.js-tippy-reviews', {
      theme: 'reviews',
      animation: 'scale',
      animateFill: false,
      maxWidth: 240,
      duration: 0,
      arrow: false,
      onShow(instance) {
        instance.popper.hidden = instance.reference.dataset.tippy ? false : true;
      	instance.setContent(instance.reference.dataset.tippy);
      }
  });
 
 $(document).ready(function(){
  $("#btn-change-data").click(function()
  {
    $(".js-tippy-reviews").attr("data-tippy",$("#test-input").val());
  })
 });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://unpkg.com/popper.js@1"></script>
<script src="https://unpkg.com/tippy.js@4"></script>

<div class="js-tippy-reviews  reviews-notification" data-tippy="test">CONTENT</div>


<input type="text" id="test-input" />
<button id="btn-change-data">Change data-tippy</button>


0
投票

这个解决方案有效

tippy('.js-tippy-reviews', {
    content: (reference) => reference.dataset.tippy,
})
© www.soinside.com 2019 - 2024. All rights reserved.