Move Image Browser

Asked

Viewed 78 times

4

I’m moving an image with mouse(mouse). When I use Chrome it works perfectly. But when I use the Firefox browser, moving the image shows the ban icon on the mouse, and moving it is different. How can I fix this?

Example: http://jsfiddle.net/g50L96e7/4/

  • MOUSEUP event is not being called in Firefox when releasing the mouse, it is only calling when clicking.

  • Use this site to check browser compatibility: http://caniuse.com/

1 answer

4


Add e.preventDefault() in all mouse events, so the default behavior of the browser will be suppressed for sure.

There is a Firefox bug about this.

That’s how it works (jsfiddle):

var svg = document.querySelector('svg');

//create circle
var shape = document.createElementNS(
    "http://www.w3.org/2000/svg", "circle");

svg.appendChild(shape);
svg.addEventListener('mousedown', mousedown);
var ddData = {
    element: null,
    initialX: 0,
    initialY: 0,
    originalX: 0,
    originalY: 0
};



//start move    
function mousedown(e) {
    e.preventDefault();
    var evt = e || window.event;
    ddData.element = evt.target || evt.srcElement;
    if (!ddData.element.id) return ddData.element = null;
    ddData.initialX = evt.clientX;
    ddData.initialY = evt.clientY;
    ddData.originalX = parseFloat(ddData.element.getAttributeNS(null, ddData.element.tagName == 'image' ? 'x' : 'cx'));
    ddData.originalY = parseFloat(ddData.element.getAttributeNS(null, ddData.element.tagName == 'image' ? 'y' : "cy"));
};

svg.onmousemove = function (e) {
    e.preventDefault();
    var evt2 = e || window.event;
    var el = ddData.element;
    if (el) {
        var posX = ddData.originalX + evt2.clientX - ddData.initialX;
        var posY = ddData.originalY + evt2.clientY - ddData.initialY;
        if (el.tagName == 'image') {
            //move object
            el.setAttributeNS(null, "x", posX);
            el.setAttributeNS(null, "y", posY);
        } 
    }
}

svg.onclick = function (e) {
    var name = this.id;
    var el = e.target;
    var x = el.getAttributeNS(null, "x");
    var y = el.getAttributeNS(null, "y");
    alert(x);
};

//stops drag movement
svg.onmouseup = function (e) {
    e.preventDefault();
    debugger;
    var evt = e || window.event;
    ddData.element = null;
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.