jQuery - 拖动div css背景

时间:2012-06-30 05:27:00

标签: jquery css background draggable

我希望能够点击div中的鼠标并移动它的背景。在谷歌搜索了很多,但没找到我想要的东西。

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

任何提示?

干杯!

4 个答案:

答案 0 :(得分:16)

好吧,让这个工作;我想我已经解决了所有问题:

带有限制限制的最终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/

答案 1 :(得分:2)

来自ui draggable demo:

拖动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/

答案 2 :(得分:0)

这篇文章是我的问题的一个很好的起点。我结合了上面的答案,另一个与获得背景图像的原始尺寸有关(SO:How do I get background image size in 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>

答案 3 :(得分:0)

我知道这是一个旧帖子,但是如果你使用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);

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