移动端js总结

本文介绍了前端开发中的一些实用技巧,包括如何判断滚动条是否到达底部,实现图片url转base64,以及Lottie动画的自定义和事件监听。同时,讨论了React中实现点击外区域隐藏组件的方法,以及处理移动设备的兼容性问题,如iOS的localStorage实时更新和安卓端的API兼容性。
摘要由CSDN通过智能技术生成

判断滚动条是否滚动到底部

// DOM元素
<div className='novelColumn__posts' id='scrollDom'>
</div>

// 监听
const scrollDom = document.getElementById('scrollDom')
scrollDom.addEventListener('scroll', this.bindHandleScroll)

// 计算
const scrollDom = document.getElementById('scrollDom')
let scrollTop = scrollDom.scrollTop
let offsetHeight = scrollDom.offsetHeight
let scrollHeight = scrollDom.scrollHeight
var bottomFlag = scrollTop+offsetHeight == scrollHeight ? true : false
console.log('滑动到底了吗---',bottomFlag)

滚动条判断不要用==,有个case只差了0.4px
也可以使用一个api IntersectionObserver API
注意:
移动端有底部安全距离:env(safe-area-inset-bottom)

body {
  padding-bottom: constant(safe-area-inset-bottom); /* 兼容 iOS < 11.2 */
  padding-bottom: env(safe-area-inset-bottom); /* 兼容 iOS >= 11.2 */
}

图片url转base64

  urlToBase64 = (url)=> {
    return new Promise ((resolve,reject) => {
        let image = new Image();
        image.onload = function() {
            let canvas = document.createElement('canvas');
            canvas.width = this.naturalWidth;
            canvas.height = this.naturalHeight;
            canvas.getContext('2d').drawImage(image, 0, 0);
            let result = canvas.toDataURL('image/png')
            resolve(result);
        };
        // CORS 策略,会存在跨域问题https://stackoverflow.com/questions/20424279/canvas-todataurl-securityerror
        image.setAttribute("crossOrigin",'Anonymous');
        image.src = url;
        image.onerror = () => {
            reject(new Error('转换失败'));
        };
    });
  }
  //使用
  this.urlToBase64(onlineBg).then(res=>{
     this.setState({base64BGurl:res})
  })

Lottie动画修改

//修改json文件内容
import acceptsuccess from '../json/suc2.json'
const asset1 = acceptsuccess.assets.find(a => a.id === 'image_2')
asset1.p = getImgUrl({id:inviteInfo?.myInfo?.avatar})
const asset2 = acceptsuccess.assets.find(a => a.id === 'image_1')
asset2.p = getImgUrl({id:inviteInfo?.fromMember?.avatar})

//给Lottie添加回调函数
<Lottie
  options={lottieOpts}
  isClickToPauseDisabled
  eventListeners={
    [
      {
        eventName: 'complete',
        callback: () => this.setState({showclose:true}),
      },
      {
        eventName:'DOMLoaded',
        callback:()=>{
          const element1 = document.getElementById("rightCpAvatar");
          const defsElementright = this.createDefElement('right')
          element1.appendChild(defsElementright);
          element1.querySelector("image").setAttribute('clip-path', 'url(#cut-off-bottom-right)');
          const element2 = document.getElementById("leftCpAvatar");
          const defsElementleft = this.createDefElement('left')
          element2.appendChild(defsElementleft);
          element2.querySelector("image").setAttribute('clip-path', 'url(#cut-off-bottom-left)');
        }
      }
    ]
  }
/>

//创建svg dom
//createElement会自动将标签名称改为小写,所以需要createElementNS创建
createDefElement = (str) => {
  const svgNs = "http://www.w3.org/2000/svg";
  const def = document.createElement会自动将标签名称改为小写,所以需要(svgNs, 'defs');
  const clipPath = document.createElementNS(svgNs, 'clipPath');
  const circle = document.createElementNS(svgNs, 'circle');

  clipPath.setAttribute('id', 'cut-off-bottom-'+str)
  circle.setAttribute('cx', 55)
  circle.setAttribute('cy', 55)
  circle.setAttribute('r', 55)
  clipPath.appendChild(circle);
  def.appendChild(clipPath)
  return def;
}

Lottie加载带有image文件夹的json文件失败

  • 查看是否图片路径问题
  • 讲文件夹图片换成线上链接

实现点击别处消失

主要通过监听目标父级dom的mouseup事件实现
方法一:判断元素是否目标元素

//dom
<div className="AnswerBook__Modal" onMouseUp={(e) => alertMouseup(e)}>
  <div className="explainAlartBox" id="explainAlartBox">
    <img
      className="step4bg"
      src={questionimg}
      style={{display: 'none'}}
      alt=""
    />
    <p>
      啦啦啦啦。
    </p>
  </div>
</div>
//js
const alertMouseup = (e) => {
  const dom = document.getElementById('explainAlartBox')
  if (showAlert && e.target != dom && e.target.parentElement != dom) {
    setShowAlert(false)
    onCancel()
  }
}

方法二:判断点击位置是否目标区域

//dom
<div className="AnswerBook__Modal" onMouseUp={(e) => alertMouseup(e)}>
  <div className="explainAlartBox" id="explainAlartBox">
    <img
      className="step4bg"
      src={questionimg}
      style={{display: 'none'}}
      alt=""
    />
    <p>
      啦啦啦啦。
    </p>
  </div>
</div>
//js
const alertMouseup = (e) => {
  const dom = document.getElementById('explainAlartBox')
    const rect = dom.getClientRects()
    if (
      e.clientX <= rect[0].x ||
      e.clientX >= rect[0].x + rect[0].width ||
      e.clientY <= rect[0].y ||
      e.clientY >= rect[0].y + rect[0].height
    ) {
      this.setState({showShareImg: false})
    }
}

react事件流

react默认是冒泡事件,监听方法为onClick
要监听捕获事件则,监听方法为 onClickCapture
阻止默认事件:

if (e.stopPropagation) {
      e.stopPropagation()
    } else {
      e.cancelBubble = true //IE阻止冒泡方法
    }
    e.stopImmediatePropagation()
  }

双端兼容性问题

  1. ios端 localStorage不能实时更新,需要退出重新页面才能拿到最新 localStorage的值
  2. 安卓端不兼容2个API: toLocaleDateString replaceAll
  3. iOS端打开包含中文的URL会白屏(浏览器和安卓正常),需要decode一下
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值