背景图像被裁剪为可拖动 div

Background image clipped to draggable div

我正在尝试制作这个东西,我有一个 div 和一个完整的背景图像,上面有一个 div 和一个容器,这个 div 是可拖动的,拖动时显示与背景相同的图像,但有所改变。

好吧,这pen

我的 CSS 到目前为止:

.contain{
    position:relative;
}

#dummy{ 
    background:url(http://i.imgur.com/CxYGDBq.jpg);
    background-attachment:fixed;
    background-repeat:no-repeat;
    background-size:cover;
    position:absolute;
    top:0;
    left:0;
}

#dummy2{
    position:absolute;
    top:0;
    z-index:99;
    left:0;
}

.mao{
    background: url(http://i.imgur.com/UbNyhzS.png);
    width:250px;
    height:300px;
    position:absolute;
    bottom:0;
    z-index:999;
    background-size:contain;
}

.screen{
    width:960px;
    height:995px;
    background-color:pink;
    position:relative;
    left:32px;
    top:30px;
    background-attachment:fixed;
    background: url(http://i.imgur.com/yjR8SCL.jpg);

}

对于我假设你想要做的事情,我已经编辑了你的笔以反映适当的变化。可以看到here.

嵌套不当 改变的第一件事是将您希望可拖动的 <div class="mao"></div> 的 div 切换为 <div class="screen"></div> 元素的子元素。

CSS 图片 URLs 需要注意的另一件事 - 在 CSS 中指定 URL 时,您需要将其括在引号内。这些"$url_here"

如果我正确理解您的要求,您可以通过查找可拖动对象移动时的当前位置,然后使用这些值设置 screenbackground-position' s背景,给人一种X光眼镜的效果。

var imageOffset = {
    top: 30,
    left: 32
};

$(function() {
    var screenHeight = $('body').height() - 300; // 300: moa height

    $(".screen").css('background-position', -(imageOffset.left) + 'px ' + -(screenHeight + imageOffset.top) + 'px');

    $(".mao").draggable({
        axis: "x",
        drag: function(event, ui) {
            $(".screen").css('background-position', -(ui.position.left + imageOffset.left) + 'px ' + -(ui.position.top + imageOffset.top) + 'px');
        }
    });
})

代码笔示例:http://codepen.io/anon/pen/JWxwzK?editors=0000

您还可以使用同一段代码将手限制在屏幕的 left/right 边界。在官方文档中有一个代码示例可以做到这一点:http://api.jqueryui.com/draggable/#event-drag