js原生--可拖拽按钮

直接看代码吧


```javascript
var bodyWidth=document.body.clientWidth; //获取文档宽度
    document.getElementById("btnHome").style.left=bodyWidth-63+"px";
    //getOffsetSum 获取相对与document的偏移量
    function getOffsetSum(ele){
        var top= ele.offsetTop,left=ele.offsetLeft;
        return { top:top, left:left }
    }
    var maindiv=document.getElementById("btnHome");//这是你想操作的元素
    maindiv.addEventListener("touchmove",touch,false);//监听事件
 
    function touch(e)
    {
        switch(e.type)
        {
            case "touchmove":
                var ele=getOffsetSum(e.target);
                var left=ele.left;
                var top=ele.top;
                var x=e.touches[0].clientX-left/2;
                var y=e.touches[0].clientY-top/2;
                e.preventDefault();
 
                if (x < 100) {
                    e.target.parentNode.style.left="0";
                }else if (x >300) {
                    e.target.parentNode.style.left=bodyWidth-63+"px";
                }else{
                    e.target.parentNode.style.left=x+"px";
                }
                if (y < 100) {
                    e.target.parentNode.style.top = "30%";
                }else if(y > 500){
                    e.target.parentNode.style.top = "80%";
                }else{
                    e.target.parentNode.style.top = y+"px";
                }
                setCookie('touch_x',e.target.parentNode.style.left);
                setCookie('touch_y',e.target.parentNode.style.top);
        }
    }
    //固定此按钮
    var touch_x = getCookie('touch_x');
    var touch_y = getCookie('touch_y');
    var btnFloat = document.getElementById('btnHome');
    if(touch_x){
        btnFloat.style.left = touch_x;
    }
    if(touch_y){
        btnFloat.style.top = touch_y;
    }
var username=document.cookie.split(";")[0].split("=")[1];
    //JS操作cookies方法!
    //写cookies
    function setCookie(name,value)
    {
        var Days = 30;
        var exp = new Date();
        exp.setTime(exp.getTime() + Days*24*60*60*1000);
        document.cookie = name + "="+ escape (value) + ";expires=" + exp.toGMTString()+";path=/";
    }
    //读cookies
    function getCookie(name)
    {
        var arr,reg=new RegExp("(^| )"+name+"=([^;]*)(;|$)");
        if(arr=document.cookie.match(reg))
            return unescape(arr[2]);
        else
            return null;
    }


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

玖逸少女梦

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值