尝试将拖动边界添加到溢出时隐藏的图像

时间:2018-04-12 15:21:26

标签: javascript html css draggable

我试图为此代码添加边界,我可以拖动图片以查看哪些部分被隐藏而不会以背景可见的方式拖动太多部分 这意味着当图像的下边界到达容器的下边界时,它停止向该方向移动



var offset = [0,0];
var mouse_is_down = false

function copie_click(elem, e) {
    mouse_is_down = true;
    offset = [elem.offsetLeft - e.clientX, elem.offsetTop - e.clientY];
}

function copie_unclick(elem, e) {
    mouse_is_down = false;
}

function copie_move(elem, e) {
    e.preventDefault(); // if this is removed mouse will unclick on move
    if (mouse_is_down) {
        elem.style.left = (e.clientX + offset[0]) + 'px';
        elem.style.top  = (e.clientY + offset[1]) + 'px';
    }
}

.mark_item_large {
    width: 200px;
    height: 200px;
    margin: 0 auto;
    padding: 1em;
    border-radius: 10px;
    margin-bottom: 0.5em;
    font-weight: 700;
    border: 1px solid black;
}

.mark_item_image {
    width: 100%;
    position: relative;
    height: 100%;
    overflow: hidden;
}

.mark_item_image > img {
    position: absolute;
    right: 0;
    top: 0;
    width: 200%;
}

        <div class="mark_item_large">
            <div class = "mark_item_image">
                <img src="https://static.wixstatic.com/media/f844a81ff14743ba92ef5f4f498aa2c8.jpeg/v1/fill/w_940,h_495,al_c,q_85,usm_0.66_1.00_0.01/f844a81ff14743ba92ef5f4f498aa2c8.webp" alt="copie preview" onmousedown="copie_click(this, event)" onmouseup="copie_unclick(this, event);" onmousemove="copie_move(this, event);">
            </div>
            .... other stuff here
        </div>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:0)


这样做我解决了我的自我!

function copie_click(elem, e) {
    mouse_is_down = true;
    offset = [elem.offsetLeft - e.clientX, elem.offsetTop - e.clientY];
}

function copie_unclick(elem, e) {
    mouse_is_down = false;
}

function copie_move(elem, e) {
    e.stopPropagation();
    e.preventDefault(); // if this is removed mouse will unclick on move
    if (mouse_is_down) {
        if ((e.movementX > 0 && e.target.offsetLeft < 0 ) || (e.movementX < 0 && -e.target.offsetLeft < (e.target.offsetWidth - e.target.parentElement.offsetWidth)))
            elem.style.left = (e.clientX + offset[0]) + 'px';
        if ((e.movementY > 0 && e.target.offsetTop < 0 )|| (e.movementY < 0 && e.target.offsetTop > -(e.target.offsetHeight - e.target.parentElement.offsetHeight) ) )
            elem.style.top  = (e.clientY + offset[1]) + 'px';
    }
    disable_click = true;
}
相关问题