質問

I am new to Javascript/JQuery. I want to know how I could modify table cell highlighting shown here http://jsfiddle.net/Brv6J/ with a modification that will allow selection in a square pattern.

For example, consider A, B, C, D, G, H and I as table cells. Dragging the mouse along the diagonal from A to E should select cells A,B,D & E

A B C 
D E F 
G H I 
役に立ちましたか?

解決

For more user friendly in selecting calendar cells, I recommend this one eHighLight Plugin. A very easy and tiny plugin for document element high lighting

他のヒント

I wrote script before for calendar select. I hope this is helpful for you.

Script:

$(function () {
    $("#table td")
        .mousedown(rangeMouseDown)
        .mouseup(rangeMouseUp)
        .mousemove(rangeMouseMove);
});

var dragStart = 0;
var dragEnd = 0;
var isDragging = false;

function rangeMouseDown(e) {
    if (isRightClick(e)) {
        return false;
    } else {
        var allCells = $("#table td");
        dragStart = allCells.index($(this));
        isDragging = true;

        if (typeof e.preventDefault != 'undefined') { e.preventDefault(); } 
        document.documentElement.onselectstart = function () { return false; };
    } 
}

function rangeMouseUp(e) {
    if (isRightClick(e)) {
        return false;
    } else {
        var allCells = $("#table td");
        dragEnd = allCells.index($(this));

        isDragging = false;
        if (dragEnd != 0) {
            selectRange();
        }

        document.documentElement.onselectstart = function () { return true; }; 
    }
}

function rangeMouseMove(e) {
    if (isDragging) {
        var allCells = $("#table td");
        dragEnd = allCells.index($(this));
        selectRange();
    }            
}

function selectRange() {
    $("#table td").removeClass('selected');
    if (dragEnd + 1 < dragStart) { // reverse select
        $("#table td").slice(dragEnd, dragStart + 1).addClass('selected');
    } else {
        $("#table td").slice(dragStart, dragEnd + 1).addClass('selected');
    }
}

function isRightClick(e) {
    if (e.which) {
        return (e.which == 3);
    } else if (e.button) {
        return (e.button == 2);
    }
    return false;
}

CSS:

#table { border:1px solid #ccc; }
#table td { padding:50px; }
#table td.selected { background-color:#ccc; }

HTML:

<table id="table">
  <tr>
    <td>A</td>
    <td>B</td>
    <td>C</td>
  </tr>
  <tr>
    <td>D</td>
    <td>E</td>
    <td>F</td>
  </tr>
  <tr>
    <td>G</td>
    <td>H</td>
    <td>I</td>
  </tr>
</table>

I create fiddle at http://jsfiddle.net/5VXDt/1/

Script can be improved with adding click event deselect or select one cell.

JQuery Selectable probably fits the requirements better.

You can use jquery jquery.ui.draggable.js

 $('td').draggable({
    start  : function (event, ui) {
        // highlighting code
     },
     stop : function (event, ui) {
        //restore the highlighting code
     }
});
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top