首页 > Web开发 > 详细

jquery: 子元素在父元素范围内拖动

时间:2020-06-16 21:54:09      阅读:73      评论:0      收藏:0      [点我收藏+]

html:

<div class="sand-content fl">
                    <img src="images/sand_900x600c.jpg" alt="" id="sandPicture">
                </div>

css:

.sand-content {
    position: relative;
    width: 600px;
    height: 400px;
    overflow: hidden;
    cursor: move;
    border: 1px solid #ddd;
}

.sand-content img {position: relative}

js:

<script>
        function justifyPicture(child) {
            let maxLeft = child.offsetParent().outerHeight() - child.outerHeight();
            let maxTop = child.offsetParent().outerWidth() - child.outerWidth();
            child.css({
                left: maxLeft / 2 + px,
                top: maxTop / 2 + px
            })
        }

        function dragPicture(moveObj) {
            let maxLeft = moveObj.offsetParent().outerWidth() - moveObj.outerWidth();
            let maxTop = moveObj.offsetParent().outerHeight() - moveObj.outerHeight();
            moveObj.on(mousedown, event => {
                let imgTop = parseFloat(moveObj.css(top));
                let imgLeft = parseFloat(moveObj.css(left));
                let lastPointX = event.clientX;
                let lastPointY = event.clientY;
                $(document).on(mousemove, e => {
                    e.preventDefault();
                    let changeX = e.clientX - lastPointX;
                    let changeY = e.clientY - lastPointY;
                    let disX = imgLeft + changeX;
                    let disY = imgTop + changeY;
                    moveObj.css({
                        left: Math.max(Math.min(disX, 0), maxLeft) + "px",
                        top: Math.max(Math.min(disY, 0), maxTop) + "px"
                    })
                })
            });
            $(document).on(mouseup, () => {
                $(document).off(mousemove);
            })
        }

        $(document).ready(function () {
            let child = $(#sandPicture);
            justifyPicture(child)
            dragPicture(child)
        })
    </script>

 

jquery: 子元素在父元素范围内拖动

原文:https://www.cnblogs.com/Nyan-Workflow-FC/p/13144744.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!