【问题标题】:Move SVG element without Jquery UI在没有 Jquery UI 的情况下移动 SVG 元素
【发布时间】:2015-11-28 07:11:20
【问题描述】:

我正在尝试使用 JQuery 使 svg 元素可拖动(无 UI)我找到了这段代码 jsfiddle。我想创建类似jsfddle2 的东西。我想我不能在这样的 svg 元素上使用它。有什么制作方法吗?

function endMove() {
    $(this).removeClass('movable');
}
function startMove() {
    $('.movable').on('mousemove', function(event) {
        var thisX = event.pageX - $(this).width() / 2,
            thisY = event.pageY - $(this).height() / 2;

        $('.movable').offset({
            left: thisX,
            top: thisY
        });
    });
}
$(document).ready(function() {
    $("#testedCircle").on('mousedown', function() {
        $(this).addClass('movable');
        startMove();
    }).on('mouseup', function() {
        $(this).removeClass('movable');
        endMove();
    });

});

【问题讨论】:

    标签: javascript jquery html css svg


    【解决方案1】:

    只需为您的 svg 标签制作一个容器。这是example

    <div id="test">
     <svg width="100" height="100" id="testedCircle">
      <circle cx="50" cy="50" r="40" stroke="green" stroke-width="4" fill="yellow" />
     </svg>
    </div>
    

    【讨论】:

    • 但是当你画另一个圆圈时,我会同时移动这两个 .. 我不想移动整个 div ......只是圈自己
    【解决方案2】:

    只需使用外部 div 将您的 SVG 元素括起来,并在该外部 div 上使用可拖动功能而不是 svg 元素。您必须确保外部 div 的宽度(以 px 为单位)等于 SVG 元素的宽度。我刚刚添加了边框来查看外部 div 的位置。下面我放了完整的代码:

    HTML

    <div id="containerDiv" style="width:100px;border:solid black;">
        <svg width="100" height="100">
          <circle id="testedCircle" cx="50" cy="50" r="40" stroke="green" stroke-width="4" fill="yellow" />
        </svg>
    </div>
    

    Javascript

    function endMove() {
        $(this).removeClass('movable');
    }
    function startMove() {
        $('.movable').on('mousemove', function(event) {
            var thisX = event.pageX - $(this).width() / 2,
                thisY = event.pageY - $(this).height() / 2;
    
            $('.movable').offset({
                left: thisX,
                top: thisY
            });
        });
    }
    $(document).ready(function() {
        $("#containerDiv").on('mousedown', function() {
            $(this).addClass('movable');
            startMove();
        }).on('mouseup', function() {
            $(this).removeClass('movable');
            endMove();
        });
    
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-01-07
      • 2018-12-20
      • 2017-12-24
      • 2011-08-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多