How to get around the "negative" height and width?

I am drawing a div in a document, but it only works when the width and height are positive:

var div;

function onMouseMove (e) {
    div.height(parseInt(e.pageY) - parseInt(div.css("top")) );
    div.width( parseInt(e.pageX) - parseInt(div.css("left")));
    console.log(div.width());
    console.log(div.height());
};

$(document).on("mousedown", function(e){
    div = $("<div></div>").prependTo("body");
    div.css({
        "top": e.pageY,
        "left": e.pageX
    });
    $(this).on("mousemove", onMouseMove);
});

$(document).on("mouseup", function(){
    setTimeout(function(){
        div.remove();
    }, 1000);
    $(this).off("mousemove", onMouseMove);
});

      

violin here

How do I do this if the width and height become negative?

Thanks in advance.

+3


source to share


2 answers


You need to add Math.abs and do something like this:

var div;
var startX = 0 / 1;
var startY = 0 / 1;

function onMouseMove(e) {
  div.height(Math.abs(parseInt(e.pageY)-parseInt(div.css("top"))));
  div.width(Math.abs(parseInt(e.pageX) - parseInt(div.css("left"))));


  if (parseInt(e.pageY) < startY) {
    div.css({
        "top": e.pageY
    });
   div.height(Math.abs(parseInt(e.pageY)-startY));
  }
 if (parseInt(e.pageX) < startX) {
    div.css({
        "left": e.pageX
    });
        div.width(Math.abs(parseInt(e.pageX) - startX));
}

  console.log(div.width());
  console.log(div.height());
  console.log(e.pageX + '<--x y--> ' + e.pageY)
};

$(document).on("mousedown", function (e) {
div = $("<div></div>").prependTo("body");
startX = parseInt(e.pageX);
startY = parseInt(e.pageY);
div.css({
    "top": e.pageY,
        "left": e.pageX
});
$(this).on("mousemove", onMouseMove);
});

$(document).on("mouseup", function () {
setTimeout(function () {
    div.remove();
}, 1000);
$(this).off("mousemove", onMouseMove);
});

      



example script

+1


source


Negative height and width are not accepted by the CSS / HTML standards. Most web browsers completely ignore the value if it's less than 0. It doesn't really make sense to have a negative height / width.

If you are trying to "invert" a div or translate it, I would recommend using a CSS3 property, transform

or perhaps even negative margins (although they are discouraged).

You can specify things like:

transform: translateY(-50px);

      

or

transform: rotateY(30deg);

      



or

margin: -50px 0 0 0; /* this acts the same as the first transform */

      

To move objects on the page after size and position have been calculated. So, for example, to "invert" a div upwards, you can rotate the div around the x-axis, making the entire div appear upside down.

Note that while this will work on its own, if you want a more 3D look of these transforms, you need to have a wrapper div that has a property viewport: [amount]px;

.

Hope this helps!

+1


source







All Articles