jQuery - 可缩放的可拖动 div

标签 jquery css jquery-ui zooming jquery-ui-draggable

这是我的代码:

http://jsfiddle.net/652nk/

HTML

<div id="canvas">
    <div id="dragme"></div>
</div>

CSS

#canvas {
    width:500px;
    height:250px;
    border:1px solid #444;
    zoom:0.7;
}
#dragme {
    width:100px;
    height:50px;
    background:#f30;
}

JS

$(function(){
    $('#dragme').draggable({containment:'parent'})
})

我在使用 css zoom 属性时遇到了一个主要问题。目标可拖动 div 的位置与光标位置不协调。

有没有干净简单的解决方案?我应该能够动态更改缩放比例。

最佳答案

您不需要设置缩放属性。我只是将差异添加到由于缩放属性而发生的可拖动位置。希望对您有所帮助。

fiddle

http://jsfiddle.net/TqUeS/

JS

var zoom = $('#canvas').css('zoom');
var canvasHeight = $('#canvas').height();
var canvasWidth = $('#canvas').width();

$('#dragme').draggable({
    drag: function(evt,ui)
    {
        // zoom fix
        ui.position.top = Math.round(ui.position.top / zoom);
        ui.position.left = Math.round(ui.position.left / zoom);

        // don't let draggable get outside the canvas
        if (ui.position.left < 0) 
            ui.position.left = 0;
        if (ui.position.left + $(this).width() > canvasWidth)
            ui.position.left = canvasWidth - $(this).width();  
        if (ui.position.top < 0)
            ui.position.top = 0;
        if (ui.position.top + $(this).height() > canvasHeight)
            ui.position.top = canvasHeight - $(this).height();  

    }                 
});

关于jQuery - 可缩放的可拖动 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8605439/

相关文章:

文本后面的 JQuery Accordion 图标

javascript - 将两个 onLoad 脚本合并为一个

jquery - Rails 4 无效AuthenticityToken

javascript - 如何用另一个元素包装html中的所有文本?

javascript - 如何添加if条件

jquery - 视差滚动网站(stellar.js)中对象的不一致定位

javascript - slider 需要超时功能动画

javascript - 将鼠标悬停在子元素上并在父元素上附加 scss

javascript - jQuery UI 工具提示点击后不会消失

javascript - 我应该在哪里调用 getUserProperties 函数?