【菜鸟搭建react项目之路15】做一个移动端的可移动浮标

今天说一个在移动端可移动浮标按钮的react实现

中心思想就是利用浮标的left、top样式来控制浮标移动。

HTML代码:

<div
  id="ballId"
  onTouchStart={(e) => {
    e.stopPropagation();
  }}
  onTouchMove={(e) => {
    e.stopPropagation();
    this.moveBtn(e);
  }}
  onTouchEnd={(e) => {
    e.stopPropagation();
  }}
>
  <h2>历史</h2>
</div>

JavaScript代码:

moveBtn = (e) => {
  if (e.targetTouches.length === 1) {
    const touch = e.targetTouches[0];
    // 控制左右移动,不允许超出视图框
    const rEdges =
      document.documentElement.clientWidth - e.currentTarget.clientWidth; // 浮标右边缘
    const eLeft = touch.clientX - e.currentTarget.clientWidth / 2;
    if (eLeft < 0) {
      e.currentTarget.style.left = 0;
    } else if (eLeft > rEdges) {
      e.currentTarget.style.left = rEdges + "px";
    } else {
      e.currentTarget.style.left =
        touch.clientX - e.target.clientWidth / 2 + "px";
    }
    // 控制上下移动,,不允许超出视图框
    const bottomEdges =
      document.documentElement.clientHeight - e.currentTarget.clientHeight; // 浮标底边缘
    const eTop = touch.clientY - e.currentTarget.clientHeight / 2;
    if (eTop < 0) {
      e.currentTarget.style.top = 0;
    } else if (eTop > bottomEdges) {
      e.currentTarget.style.top = bottomEdges + "px";
    } else {
      e.currentTarget.style.top =
        touch.clientY - e.target.clientHeight + "px";
    }
  }
};

CSS样式:

#ballId {
  position: fixed;
  background: rgb(19, 167, 19);
  color: white;
  width: 100px;
  text-align: center;
  height: 100px;
  border-radius: 50%;
  box-shadow: 5px 5px 40px rgba(0, 0, 0, 0.5);
  /* 过渡效果在IE下展示效果不友好 */
  transition: all 0.08s;
  top: 100px;
  left: 100px;
  h2 {
    margin: 0;
    padding: 0;
    line-height: 100px;
    user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    -webkit-user-select: none;
  }
}
posted @ 2022-01-18 16:45  leah-xx  阅读(98)  评论(0编辑  收藏  举报