jQuery实现在一个范围内拖拉的方块

时间:2019-10-07
本文章向大家介绍jQuery实现在一个范围内拖拉的方块,主要包括jQuery实现在一个范围内拖拉的方块使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。
<!DOCTYPE html>
<html>
<head>
    <meta charset='utf-8'>
    <meta http-equiv='X-UA-Compatible' content='IE=edge'>
    <title>
    </title>
    <meta name='viewport' content='width=device-width, initial-scale=1'>
    <link rel='stylesheet' type='text/css' media='screen' href='test.css'>
    <script src="jquery.js"> type="text/javascript"</script>
    <script src='test.js' type="text/javascript"></script>
    
</head>
<body>
    <div>
        <span></span>
    </div>
</body>
</html>
div{
    width: 800px;
    height: 600px;
    position: relative;
    background-color: aliceblue;
}
span{
    width: 100px;
    height: 100px;
    background-color: black;
    left: 0;
    position: absolute;
    top:0;
}
$(function () {
    $("span").mousedown(function () {
        $(document).mousemove(function (e) {
            var span_left = e.pageX - $("div").offset().left - $('span').width() / 2;
            var span_top = e.pageY - $("div").offset().top - $("span").height() / 2;
            if (span_left < 0) {
                span_left = 0;
            } else if (span_left > $('div').width() - $("span").width()) {
                span_left = $("div").width() - $('span').width();
            }
            if (span_top < 0) {
                span_top = 0;
            } else if (span_top > $("div").height() - $("span").height()) {
                span_top = $('div').height() - $('span').height();
            }
            $('span').css({ left: span_left, top: span_top });
        }).mouseup(function () {
            $(this).unbind('mousemove');
        })
    })
})

原文地址:https://www.cnblogs.com/tomatofjy/p/11630495.html