How to avoid choosing vertical drag and drop?

I have a dynamic table here. I have completed the selection of dragging and dropping table cells, but you need to prevent the selection of vertical drag and drop. How to avoid choosing vertical drag and drop?

My fiddle .

the code:

var isMouseDown = false;
$("#mytable td").mousedown(function () {
    isMouseDown = true;
    $(this).toggleClass("highlighted");
    return false;   // prevent text selection
}).mouseover(function () {
      if (isMouseDown) {
          $(this).toggleClass("highlighted");
      }
}).bind("selectstart", function () {
      return false;   // prevent text selection in IE
});
+4
source share
1 answer

First bindobsolete in the new versions of jQuery, instead use on.

Secondly, you can save the event parentin mousedownand check it in mouseover. This way you can check if it is tdin the same tror not. Updated code might look like this:

var isMouseDown = false, parent;

$("#mytable td").mousedown(function () {
    var $this = $(this);
    isMouseDown = true;
    parent = $this.closest('tr').get(0);
    $this.toggleClass("highlighted");
    return false;   // prevent text selection
}).mouseover(function () {
    var $this = $(this);
    if (isMouseDown && parent === $this.closest('tr').get(0)) {
        $this.toggleClass("highlighted");
    }
}).on("selectstart", function () {
    return false;   // prevent text selection in IE
});

Jsfiddle

Update:

. , mouseenter ( mouseover) mousedown. , .

JSFiddle:

var isMouseDown = false,
    $cells = $('#mytable td');

$cells.on('mousedown', function() {
    $cells.removeClass('highlighted');    // Clear previous selection
    isMouseDown = true;

    $(this)
        .toggleClass('highlighted')
        .siblings('td')
        .on('mouseenter', onMouseEnter);    // Add mouseenter event handler on siblings

    return false;
}).on('mouseup', function() {
    $(this).siblings('td').off('mouseenter');    // Remove mouseenter event handler from siblings
}).on('selectstart', function() {
    return false;
});

// The onMouseEnter handler
function onMouseEnter() {
    if (isMouseDown) {
        $(this).toggleClass("highlighted");
    }
}
+3

All Articles