js,e.pageX、pageY模态框拖动

手写模态框拖动功能

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
	<style type="text/css">
		.tk-modal{
			position: absolute;
			width: 300px;
		}
		.tk-modal-header{
			border: 1px solid #ccc;
			width: 200px;
		}
		.tk-modal-close{
			width: 50px;
		}
	</style>
</head>
<body>
	<div class="tk-modal tk-ask-modal">
		<div class="tk-modal-header">
			<div class="tk-modal-close fright">关闭</div>
		</div>
		<div class="tk-modal-maintk-modal-main"></div>
	</div>

<script type="text/javascript" src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
	$(function(){
		// 模态窗
    // 模态窗关闭
    tkModalOpen($(".tk-ask-modal"));
    $(document).on("click",".tk-modal-close,.tk-modal-footer-cancel",function(){
        tkModalClose($(this).parents(".tk-modal"));
    });

    var _move=false;//移动标记
    var _x,_y;//鼠标离控件左上角的相对位置
    $(document).on("click",".tk-modal-header",function(){
        //alert("click");//点击(松开后触发)
    }).on("mousedown",".tk-modal-header",function(e){
        _move=true;
        _x=e.pageX-parseInt($(this).parent(".tk-modal").css("left"));
        _y=e.pageY-parseInt($(this).parent(".tk-modal").css("top"));
        // console.log(_x+_x)
    });
    $(document).mousemove(function(e){
        if(_move){
            var x=e.pageX-_x;//移动时根据鼠标位置计算控件左上角的绝对位置
            var y=e.pageY-_y;
            $(".tk-modal").css({top:y,left:x});//控件新位置
             // console.log(x)
        }
    }).mouseup(function(){
        _move=false;
    });
    // 打开模态框
    function tkModalOpen(obj){
        $(".tk-overlay").show();
        $("body").height($(window).height()).css({
            "overflow-y": "hidden"
        });
        $left=(document.body.clientWidth-obj.width())/2;
        $top=document.body.clientHeight>obj.height()?(document.body.clientHeight-obj.height())/2:0;
        obj.css({"left":$left,"top":$top});
        obj.show();
    };
    // 关闭模态框
    function tkModalClose(obj){
        obj.hide();
        $(".tk-overlay").hide();
        $("body").css({
            "overflow-y": "visible"
        });
    };
	})
</script>	
</body>
</html>
已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页