首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使div出现在选定的文本上?

如何使div出现在选定的文本上?
EN

Stack Overflow用户
提问于 2018-07-15 21:21:50
回答 1查看 884关注 0票数 1

我正在使用VueJS创建一个应用程序,通过用户选择的文本生成工具提示。我希望在用户选择的文本上准确地显示工具提示。我正在使用Tippy.js创建工具提示

以下是代码:

代码语言:javascript
复制
const giphy = require('giphy-api')('Here goes the API key');

export default {
  data () {
    return {
      
    }
  },

  mounted() {
    const template = document.querySelector('#template');
    const initialText = template.textContent;
    
    let that = this;

    const tip = tippy('.tip', {
      animation: 'shift-toward',
      arrow: true,
      html: '#template',
      trigger: 'click',
      onShow() {
        
        // `this` inside callbacks refers to the popper element
        const content = this.querySelector('.tippy-content');
        
        if(tip.loading || content.innerHTML !== initialText) 
          return;
        
        tip.loading = true;

        var self = that;
        
        $('#app').mouseup(function() {
          let selection = self.getSelected();

          if (selection != "") {

            giphy.translate(`${selection}`)
            .then(function (response) {
              // Assigning the url from response object to the url
              const url = response.data.images.fixed_width_small.url;
              content.innerHTML = `<img width="100" height="100" src="${url}">`
              tip.loading = false
            })
            .catch(function(error){
              content.innerHTML = 'Loading failed'
              tip.loading = false
            });

          }
        });
      },

      onHidden() {
        const content = this.querySelector('.tippy-content');
        content.innerHTML = initialText;
      }
    })

  },

  methods: {
    // Function to get the selected text
    getSelected() {
      let selectedText = "", selection;
      
      if (window.getSelection) {
        selectedText = "" + window.getSelection();
      } 
      else if ( (selection = document.selection) && selection.type == "Text") {
        selectedText = selection.createRange().text;
      }
      return selectedText;
    }

  }
代码语言:javascript
复制
#app {
  font-family: 'Avenir', Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 250px;
}
代码语言:javascript
复制
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="app">
    <div class="tip">
      <h1>Fifa World Cup 2018</h1>
      <h4 style="margin-top:40px;">Winner is France</h4>
      <span style="margin-top:10px;">Runner up is Croatia</span>
    </div>

    <div>
      <div id="template" style="display: none">
        Loading tooltip...
      </div>
    </div>

  </div>

带有id=“模板”的div是形成工具提示的div。到目前为止,我只设法将它显示在文本所在的div的中心。如何确保工具提示完全显示在选定文本的上方?有人能帮帮我吗?

EN

回答 1

Stack Overflow用户

发布于 2018-07-15 21:55:39

  1. 在app上注册mouseup事件处理程序
  2. 在处理程序中调用window.getSelection().getRangeAt(0).getBoundingClientRect()以获得文本选择的边框。
  3. 将文本选择的边框作为“虚拟元素”( docs:https://atomiks.github.io/tippyjs/ (crtl+f "virtual“)传递给tippy )。

香草JS前两个步骤的例子:

代码语言:javascript
复制
let p = document.querySelector('p');
let div = document.querySelector('div');

document.documentElement.addEventListener('mouseup', () => {
    console.log(p);
    let selection = getSelection();
    console.log(selection);
    if (!selection.isCollapsed && selection.rangeCount > 0) {
        let range = selection.getRangeAt(0);
        console.log(range);
        let rangeRect = range.getBoundingClientRect();
        console.log(rangeRect);
        console.log(div);
        div.style.top = rangeRect.top+'px';
        div.style.left = rangeRect.left+'px';
        div.style.width = rangeRect.width+'px';
        div.style.height = rangeRect.height+'px';
    } else {
        div.style.top = 0;
        div.style.left = 0;
        div.style.width = 0;
        div.style.height = 0;
    }
});
代码语言:javascript
复制
body {
    padding: 20px;
    position: relative;
}

div {
    border: 2px red solid;
    position: absolute;
    pointer-events: none;
    top: -999px;
    left: -999px;
}

p {
    width: 500px;
}
代码语言:javascript
复制
<div></div>
<h1> try selecting some of the text below </h1>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
</p>

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51352337

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档