经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » HTML/CSS » HTML5 » 查看文章
html5实现可拖拽移动的悬浮图标的示例代码
来源:jb51  时间:2021/3/29 8:52:34  对本文有异议

h5 上经常会有这样的需求:

需要在页面上加上一个悬浮图标,大致是如下图的最终实现

但是往往按照设计稿是不会遮住主体区域的,但是实际上有时候偏偏会遮挡主体区域,但是为了更好的点击量,又不得不悬浮在页面上...

如果能让图标可拖拽移动,这样在遮住主体区域之后,用户可自由移动,这种方案及可以兼顾了。

实现的效果如下:

(和微信的浮窗效果类似,左右位置靠边显示,上下位置随意放)

话不多说,上代码了

  1. <div class="ys-float-btn"
  2. :style="{'width': itemWidth+'px','height': itemHeight+'px','left': left+'px','top': top+'px'}"
  3. ref="div"
  4. @touchstart.prevent="(e) => {dragStart(e)}"
  5. @touchend.prevent="(e) => {dragEnd(e)}"
  6. @touchmove.prevent="(e) => {dragProgress(e)}"
  7. >
  8. <img src="./../assets/fc-icon.png" />
  9. </div>
  1. // 代码直接在 vue 项目里,可自行改为js/jquery 写法
  2. data () {
  3. return {
  4. gapWidth: 10,
  5. itemWidth: 20, // 图标的宽度
  6. itemHeight: 30 // 图标的高度
  7. }
  8. },
  9. created() {
  10. this.clientWidth = document.documentElement.clientWidth;
  11. this.clientHeight = document.documentElement.clientHeight;
  12. this.left = this.clientWidth - this.itemWidth - this.gapWidth;
  13. this.top = this.clientHeight*0.8; }
  14. methods: {
  15. dragStart(e) {
  16. this.$refs.div.style.transition = 'none';
  17. },
  18. dragEnd(e) {
  19. this.$refs.div.style.transition = 'all 0.3s';
  20. if (this.left > this.clientWidth/2) {
  21. this.left = this.clientWidth - this.itemWidth - this.gapWidth;
  22. } else {
  23. this.left = this.gapWidth;
  24. }
  25. },
  26. dragProgress(e) {
  27. if (e.targetTouches.length === 1) {
  28. let touch = event.targetTouches[0];
  29. this.left = touch.clientX - this.itemWidth/2;
  30. this.top = touch.clientY - this.itemHeight/2;
  31. }
  32. }
  33. }

以上代码既可以上下也可以左右移动,如果只想让可上下移动,就去掉 left 相关的设置和计算。

到此这篇关于html5实现可拖拽移动的悬浮图标的示例代码的文章就介绍到这了,更多相关html5可拖拽悬浮图标内容请搜索w3xue以前的文章或继续浏览下面的相关文章,希望大家以后多多支持w3xue!

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号