jQuery的 - 拖动DIV + CSS背景(jQuery - drag div css back

2019-06-25 21:53发布

我希望能够点击握住我的鼠标一个div内移动它的背景。 搜查谷歌很多,并没有找到我想要的东西。

这里的目标(显示的地图是拖动对象): http://pontografico.net/pvt/gamemap/

有小费吗?

干杯!

Answer 1:

好了,得到这个工作; 我想我得到了所有琐碎的问题:

最终的jQuery有边界限制

$(document).ready(function(){
    var $bg = $('.bg-img'),
        elbounds = {
            w: parseInt($bg.width()),
            h: parseInt($bg.height())
        },
        bounds = {w: 2350 - elbounds.w, h: 1750 - elbounds.h},
        origin = {x: 0, y: 0},
        start = {x: 0, y: 0},
        movecontinue = false;

    function move (e){
        var inbounds = {x: false, y: false},
            offset = {
                x: start.x - (origin.x - e.clientX),
                y: start.y - (origin.y - e.clientY)
            };

        inbounds.x = offset.x < 0 && (offset.x * -1) < bounds.w;
        inbounds.y = offset.y < 0 && (offset.y * -1) < bounds.h;

        if (movecontinue && inbounds.x && inbounds.y) {
            start.x = offset.x;
            start.y = offset.y;

            $(this).css('background-position', start.x + 'px ' + start.y + 'px');
        }

        origin.x = e.clientX;
        origin.y = e.clientY;

        e.stopPropagation();
        return false;
    }

    function handle (e){
        movecontinue = false;
        $bg.unbind('mousemove', move);

        if (e.type == 'mousedown') {
            origin.x = e.clientX;
            origin.y = e.clientY;
            movecontinue = true;
            $bg.bind('mousemove', move);
        } else {
            $(document.body).focus();
        }

        e.stopPropagation();
        return false;
    }

    function reset (){
        start = {x: 0, y: 0};
        $(this).css('backgroundPosition', '0 0');
    }

    $bg.bind('mousedown mouseup mouseleave', handle);
    $bg.bind('dblclick', reset);
});

http://jsfiddle.net/userdude/q6r8f/4/


原来的答案

HTML

<div class="bg-img"></div>

CSS

div.bg-img {
    background-image: url(http://upload.wikimedia.org/wikipedia/commons/9/91/Flexopecten_ponticus_2008_G1.jpg);
    background-position: 0 0;
    background-repeat: no-repeat;
    background-color: blue;
    border: 1px solid #aaa;
    width: 250px;
    height: 250px;
    margin: 25px auto;
}

jQuery的

$(document).ready(function(){
    var $bg = $('.bg-img'),
        origin = {x: 0, y: 0},
        start = {x: 0, y: 0},
        movecontinue = false;

    function move (e){
        var moveby = {
            x: origin.x - e.clientX,
            y: origin.y - e.clientY
        };

        if (movecontinue === true) {
            start.x = start.x - moveby.x;
            start.y = start.y - moveby.y;

            $(this).css('background-position', start.x + 'px ' + start.y + 'px');
        }

        origin.x = e.clientX;
        origin.y = e.clientY;

        e.stopPropagation();
        return false;
    }

    function handle (e){
        movecontinue = false;
        $bg.unbind('mousemove', move);

        if (e.type == 'mousedown') {
            origin.x = e.clientX;
            origin.y = e.clientY;
            movecontinue = true;
            $bg.bind('mousemove', move);
        } else {
            $(document.body).focus();
        }

        e.stopPropagation();
        return false;
    }

    function reset (){
        start = {x: 0, y: 0};
        $(this).css('backgroundPosition', '0 0');
    }

    $bg.bind('mousedown mouseup mouseleave', handle);
    $bg.bind('dblclick', reset);
});

http://jsfiddle.net/userdude/q6r8f/2/



Answer 2:

从UI拖动演示:

拖动DOM元素很简单,没有必要推倒重来。

<style>
#draggable { width: 150px; height: 150px; padding: 0.5em; }
</style>
<script>
    $(function() {
        $( "#draggable" ).draggable();
    });
</script>



<div class="demo">

<div id="draggable" class="ui-widget-content">
    <p>Drag me around</p>
</div>

</div><!-- End demo -->



<div class="demo-description" style="display: none; ">
<p>Enable draggable functionality on any DOM element. Move the draggable object by clicking on it with the mouse and dragging it anywhere within the viewport.</p>
</div><!-- End demo-description -->

http://jqueryui.com/demos/draggable/

编辑:一个div内可拖动的背景也是可能的。 在这里看到小提琴: http://jsfiddle.net/FyFZA/



Answer 3:

这篇文章是我的问题一个很好的起点。 我上面的回答结合起来,而另一个属于让你的背景图像的原始尺寸( SO:如何获取背景图像的大小jQuery的? )

与我的特定设置我使用background-size:cover ,所以我不得不确定背景图像的高度/宽度之比,并比较它的容器的高度/宽度之比。 这意味着每个图像仅被允许在一个维度上滑动。

在这里你们两个演员可能不需要。 我加了边框的元素,我目前操作只是为了保持很容易地看到,删除它时,我就完了。 我也更新了偏移值的输入,所以我可以将它们发送到服务器上。

我往往是非常冗长和我的意见,所以这是一个漫长的一点,但我希望它可以帮助别人。

<script>
$(document).ready(function(){

    function reset (){
        start = {x: 0, y: 0};
        $(this).css('backgroundPosition', '0 0');
    }

    $(".bg-img").bind('dblclick', reset);

    //my jquery
$(".bg-img").on('mousedown mouseup', function(e){

    //declare some vars
    var start = {x: 0, y: 0};
    var move = {x: 0, y: 0};
    var id = $(this).attr('id');

    //pointer coordinates on mousedown
    var origin = {x: 0, y: 0};

    //container dimensions
    var container = {w: $(this).width(), h: $(this).height()};

    //container ratio
    var containerRatio = container.h / container.w;

    //background image dimensions, note: this gets dimensions of unscaled image
    var img = new Image;
    img.src = $(this).css('background-image').replace(/url\(|\)$/ig, "");
    var background = {w: img.width, h: img.height};

    //background ratio
    var backgroundRatio = background.h / background.w;

    //max x and y position, aka boundary
    var min = {x: 0, y: 0};
    var max = {x: 0, y: 0};

    //move x
    if(backgroundRatio < containerRatio){
        min.y = 0;
        min.x = -((container.h * (1/backgroundRatio)) - container.w);
    }

    //move y
    else if (backgroundRatio > containerRatio){
        min.x = 0;
        min.y = -((container.w * backgroundRatio) - container.h);
    }

    //ratios are equal, don't move anything
    else{
        min.x = 0;
        min.y = 0;
    }

    //activate
    if(e.type == 'mousedown'){

        //add border so it's easier to visualize
        $(this).css('border', '1px solid #000000');

        //get current position of mouse pointer
        origin.x = e.clientX;
        origin.y = e.clientY;

        //get current background image starting position
        var temp = $(this).css('background-position').split(" ");
        start.x = parseInt(temp[0]);
        start.y = parseInt(temp[1]);

        //mouse is dragged while mousedown
        $(this).mousemove(function(e){

            //move position
            move.x = start.x + (e.clientX - origin.x);
            move.y = start.y + (e.clientY - origin.y);

            //if it's in the bounds, move it
            if(move.x <= max.x && move.x >= min.x && move.y <= max.y && move.y >= min.y){

                console.log('both');

                //alter css
                $(this).css('background-position', move.x + 'px ' + move.y + 'px');

                //update input
                $("#" + id).val('x:' + move.x + ', y:' + move.y);
            }

            //in x bound,
            else if(move.x <= max.x && move.x >= min.x){

                console.log('x');

                //below min.y
                if(move.y < min.y){
                    $(this).css('background-position', move.x + 'px ' + min.y + 'px');

                    //update input
                    $("#" + id).val('x:' + move.x + ', y:' + min.y);
                }
                //above max.y
                else if(move.y > max.y){
                    $(this).css('background-position', move.x + 'px ' + max.y + 'px');

                    //update input
                    $("#" + id).val('x:' + move.x + ', y:' + max.y);
                }
            }

            //in y bound
            else if(move.y <= max.y && move.y >= min.y){

                console.log('y');

                //below min.x
                if(move.x < min.x){
                    $(this).css('background-position', min.x + 'px ' + move.y + 'px');

                    //update input
                    $("#" + id).val('x:' + min.x + ', y:' + move.y);            
                }

                //above max.x
                else if(move.x > max.x){
                    $(this).css('background-position', max.x + 'px ' + move.y + 'px');

                    //update input
                    $("#" + id).val('x:' + max.x + ', y:' + move.y);
                }
            }

            //out of both bounds
            else{
                console.log('problem');
            }
        });
    }

    //deactivate
    else{

        //remove border
        $(this).css('border', 'none');

        //remove mousemove
        $(this).off('mousemove');
        $(document.body).focus();
    }
});
});
</script>


Answer 4:

我知道这是一个古老的职位,但如果你使用jQueryUI的另一个解决方案是在背景之上建立一个透明的元素,然后使用拖动回调更新原始节点的backgroundPosition。 下面是一个例子:

/* node is the element containing the background image */
/* width/height variables are just there if your background image is a different width/height then the container */
var transparent = $('<div></div>');
transparent.css({
    position: 'absolute',
    zIndex: 10,
    left: node.offset().left,
    top: this.node.offset().top,
    width: width || node.width(),
    height: height || node.height(),
    backgroundColor: '#fff',
    opacity: 0.2
});

$('body').append(transparent);

options.config.drag = function(event, ui) {
    node.css({ backgroundPosition: (ui.position.left - ui.originalPosition.left) + 'px ' + (ui.position.top - ui.originalPosition.top) + 'px' });
};

$(transparent).draggable(options.config);

我故意留下一个白色的背景色与不透明,所以你可以在测试时看到的元素。



文章来源: jQuery - drag div css background