vue:如何实现点击选中文字,则在旁边出现删除按钮?

如何实现点击选中文字,则在旁边出现删除按钮?
选中文字是别人写好的,那我是需要监听鼠标选中时的,相对浏览器的XY,然后显示出我的图标。但是我的图标是怎么出现的呢,图标的添加在哪?是选中的div里还是整个body?
image.png

找到想要的效果了,类似于这个。因为文字的位置不固定,图片是跟随鼠标选中的位置出现的。
我再想想怎么做出我想要的。
https://blog.csdn.net/hththth...

阅读 4.3k
2 个回答

https://codepen.io/brendanfic...

<style>
  .container {
    position: relative;
  }

  .btn {
    display: none;
    width: 50px;
    position: absolute;
  }

  .text {
    position: absolute;
    cursor: pointer;
    padding: 5px;
    border: 1px solid red;
    display: inline-block;
  }

  .text1 {
    left: 10px;
    top: 10px;
  }

  .text2 {
    left: 100px;
    top: 100px;
  }
</style>

<body>
  <div class="container">
    <span class="text text1">文字1</span>
    <span class="text text2">文字2</span>
  </div>
  <button class="btn">删除</button>
</body>
<script>
  var body = document.querySelector('body')
  var btn = document.querySelector('.btn')
  body.addEventListener('click', function (e) {
    if (e.target.className.includes('text')) {
      btn.style.left = e.pageX + 'px'
      btn.style.top = e.pageY + 'px'
      btn.style.display = 'block'
    } else if (e.target.className !== 'btn' && e.target.className !== 'container') {
      btn.style.display = 'none'
    }
  })
</script>

popper.js ?

图标肯定是插到 body 上,Vue3 有 Teleport。vue 2 你可以参考 message 组件。

位置的话就是绝对定位,然后改 left 和 top 了。

需要注意边界控制。别超出屏幕。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题