セルをドラッグで選択する方法

このQ&Aのポイント
  • セルをドラッグで選択する方法について教えてください。
  • 7×7のセルをドラッグで選択するときに、選択できない場所を作りたいと思っています。
  • (1,2)を選択できるセルの開始点として5×6の範囲で選択できるようにしたいです。
回答を見る
  • ベストアンサー

セルをドラッグで選択するときに、

7×7のセルをドラッグで選択をするときに、選択できない場所を作りたいと思っているのですが、どのようにすればいいのでしょうか? ネット上にあるサンプルでは画像の(0、0)のセルから選択できるのですが、これを(1,2)を選択できるセルの開始点として5×6の範囲で選択できるようにしたいと思っています。 </tytle>までのひながた以降のコードです。 わかる方よろしくお願いします。 <style type="text/css"> html, body{ margin: 0px; } table{ -moz-user-select: none; -khtml-user-select: none; user-select: none; width: 500px; height: 500px; } table, td, th{ margin: 10px; border-style: solid; border-color: black; border-width: 1px; } </style> <script type="text/javascript"> var startCell = null; //マウスダウンのイベント処理 function mouseDown(table, e){ if (!e) var e = window.event; startCell = e.srcElement? e.srcElement: e.target; if(startCell.tagName != "TD"){ startCell = null; return; } mouseMove(table, e); } //マウスアップのイベント処理 function mouseUp(table, e){ if (!e) var e = window.event; var endCell = e.srcElement?e.srcElement:e.target; if(!(endCell.tagName=="TD" && startCell)) return false; //セルの位置を取得 var from = getCellPos(table, startCell); var to = getCellPos(table, endCell); if(!from || !to) return false; //mouseMoveで選択状態表示の更新をさせないようにする startCell = null; //ここに選択後の処理を書く alert("("+from.col+", "+from.row+") -> ("+to.col+", "+to.row+")"); } //マウス移動のイベント処理 function mouseMove(table, e){ if (!e) var e = window.event; var endCell = e.srcElement?e.srcElement:e.target; if(!(endCell.tagName=="TD" && startCell)) return false; //セルの位置を取得 var from = getCellPos(table, startCell); var to = getCellPos(table, endCell); if(!from || !to) return false; //色を変更 var x, y, cells; for(y=0; y<table.rows.length; y++){ row = table.rows.item(y); for(x=0; x<row.cells.length; x++){ if((from.row-y)*(y-to.row)>=0 && (from.col-x)*(x-to.col)>=0) row.cells.item(x).style.backgroundColor = "#ffdddd";//選択状態の色 else row.cells.item(x).style.backgroundColor = "transparent";//未選択状態の色 } } } //tableの中のcellの位置を取得する function getCellPos(table, cell){ var pos = new Object(); if(cell.nodeName == "TD"){ var x, y, cells; for(y=0; y<table.rows.length; y++){ row = table.rows.item(y); for(x=0; x<row.cells.length; x++){ if(row.cells.item(x) == cell){ pos.row = y; pos.col = x; return pos; } } } } return null; } </script> </head> <body><!-- Google Analytics Start --> <script type="text/javascript"> var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www."); document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E")); </script> <script type="text/javascript"> try { var pageTracker = _gat._getTracker("UA-9296140-1"); pageTracker._trackPageview(); } catch(err) {} </script> <!-- Google Analytics End --> <table onmousedown="mouseDown(this, event); return false;" onmouseup="mouseUp(this, event);" onmousemove="mouseMove(this, event); return false;"> <tr> <td>(0,0)</td><td>(1,0)</td><td>(2,0)</td><td>(3,0)</td><td>(4,0)</td><td>(5,0)</td><td>(6,0)</td> </tr> <tr> <td>(0,1)</td><td>(1,1)</td><td>(2,1)</td><td>(3,1)</td><td>(4,1)</td><td>(5,1)</td><td>(6,1)</td> </tr> <tr> <td>(0,2)</td><td>(1,2)</td><td>(2,2)</td><td>(3,2)</td><td>(4,2)</td><td>(5,2)</td><td>(6,2)</td> </tr> <tr> <td>(0,3)</td><td>(1,3)</td><td>(2,3)</td><td>(3,3)</td><td>(4,3)</td><td>(5,3)</td><td>(6,3)</td> </tr> <tr> <td>(0,4)</td><td>(1,4)</td><td>(2,4)</td><td>(3,4)</td><td>(4,4)</td><td>(5,4)</td><td>(6,4)</td> </tr> <tr> <td>(0,5)</td><td>(1,5)</td><td>(2,5)</td><td>(3,5)</td><td>(4,5)</td><td>(5,5)</td><td>(6,5)</td> </tr> <tr> <td>(0,6)</td><td>(1,6)</td><td>(2,6)</td><td>(3,6)</td><td>(4,6)</td><td>(5,6)</td><td>(6,6)</td> </tr> </table> </body> </html>

質問者が選んだベストアンサー

  • ベストアンサー
  • fujillin
  • ベストアンサー率61% (1594/2576)
回答No.1

選択対象外のセルの扱いを、マウスがテーブルの外に出た時と同じ扱いにしてかまわないのなら… スクリプトの終わりの方にある function getCellPos() の中の  pos.row = y;  pos.col = x;  return pos; の部分に1行追加して pos.row = y; pos.col = x; if(2>y || 1>x) pos = null; return pos; でいけるのではないでしょうか?

kei114477
質問者

お礼

ありがとうございます^^ できました^^

関連するQ&A

  • ドラッグでセルを選択した後に

    ドラッグでセルを選択した後に、別の場所をドラッグするとその前に選択したセルの色が消えるようにしたいのですがどなたか方法がわかりますでしょうか? 施設予約サイトを作っているのですが、間違えた時間をドラッグしたときに、もう一度別のセルをドラッグすると、予約するための情報は最後にドラッグしたときの情報をとるのですが、UI的にはよくないので直したいと思っているのですが、できません。わあかるかたいたらお願いします。 ドラッグは縦一列のみできるように制限をかけています。 下は、セルをドラッグするところに関係するコードです。まだ必要なコード(仕組みが分かるコード)があるときには補足します。 var startCell = null; //マウスダウンのイベント処理 function mouseDown(table, e){ if (!e) var e = window.event; startCell = e.srcElement? e.srcElement: e.target; if(startCell.tagName != "TD"){ startCell = null; return; } mouseMove(table, e); } //マウスアップのイベント処理 function mouseUp(table, e){ if (!e) var e = window.event; var endCell = e.srcElement?e.srcElement:e.target; if(!(endCell.tagName=="TD" && startCell)) return false; //セルの位置を取得 var from = getCellPos(table, startCell); var to = getCellPos(table, endCell); if(!from || !to) return false; //mouseMoveで選択状態表示の更新をさせないようにする startCell = null; //alert("("+from.col+", "+from.row+") -> ("+to.col+", "+to.row+")"); document.form1.fromcol.value=from.col; document.form1.fromrow.value=from.row; document.form1.tocol.value=to.col; document.form1.torow.value=to.row; } //マウス移動のイベント処理 function mouseMove(table, e){ if (!e) var e = window.event; var endCell = e.srcElement?e.srcElement:e.target; if(!(endCell.tagName=="TD" && startCell)) return false; //セルの位置を取得 var from = getCellPos(table, startCell); var to = getCellPos(table, endCell); if(!from || !to || from.day != to.day) return false; //色を変更 var x, y, cells; for(y=2; y<table.rows.length; y++){ row = table.rows.item(y); for(x=0; x<row.cells.length; x++){ if((from.row-y)*(y-to.row)>=0 && (from.col-x)*(x-to.col)>=0) row.cells.item(x).style.backgroundColor = "#888888";//選択状態の色 //else // row.cells.item(x).style.backgroundColor = "transparent";//未選択状態の色 } } } //tableの中のcellの位置を取得する function getCellPos(table, cell){ var pos = new Object(); if(cell.nodeName == "TD"){ var x, y, cells; for(y=0; y<table.rows.length; y++){ row = table.rows.item(y); for(x=0; x<row.cells.length; x++){ if(row.cells.item(x) == cell){ pos.row = y; pos.col = x; if(2>y || 1>x) pos = null; pos.day = (x+1 - (x+1)%2) / 2; return pos; } } } } return null; } </script>

  • 先ほども似たような質問をしているのですが、

    画像のような画面のセルをドラッグで選択するときに、最大で2列分だけしか選択できないようにしたいと思っています。施設管理のサイトを作りたいと思っています。先ほどした質問でドラッグ できる位置を指定ができるようになったのですがドラッグできる範囲も指定したいのです。 日付をまたいで選択できないようにしたいと思っています。これは、選択しているセルは、色が変わるのですが、できれば日付をまたぐと色が変わらず、選択できないようにしたいです。 ですが選択できても、範囲を決定したときに、エラーメッセージが出てくるというような方法でもかまいません。 厚かましいかもしれませんがお願いします。 以下は </tytle>までのひながた以降のコードです。 わかる方よろしくお願いします。画像の空白部には24×30のセルがあります。 <table>~</table>の間には画像のような<td></td>のタグがあります。 よろしくお願いします。 <style type="text/css"> html, body{ margin:0px; } table{ -moz-user-select:none; -khtml-user-select:none; user-select:none; width:500px; height:500px; } table, td, th{ margin:10px; border-style:solid; border-color:black; border-width:1px; } </style> <script type="text/javascript"> var startCell = null; //マウスダウンのイベント処理 function mouseDown(table, e){ if (!e) var e = window.event; startCell = e.srcElement? e.srcElement: e.target; if(startCell.tagName != "TD"){ startCell = null; return; } mouseMove(table, e); } //マウスアップのイベント処理 function mouseUp(table, e){ if (!e) var e = window.event; var endCell = e.srcElement?e.srcElement:e.target; if(!(endCell.tagName=="TD" && startCell)) return false; //セルの位置を取得 var from = getCellPos(table, startCell); var to = getCellPos(table, endCell); if(!from || !to) return false; //mouseMoveで選択状態表示の更新をさせないようにする startCell = null; //ここに選択後の処理を書く alert("("+from.col+", "+from.row+") -> ("+to.col+", "+to.row+")"); } //マウス移動のイベント処理 function mouseMove(table, e){ if (!e) var e = window.event; var endCell = e.srcElement?e.srcElement:e.target; if(!(endCell.tagName=="TD" && startCell)) return false; //セルの位置を取得 var from = getCellPos(table, startCell); var to = getCellPos(table, endCell); if(!from || !to) return false; //色を変更 var x, y, cells; for(y=0; y<table.rows.length; y++){ row = table.rows.item(y); for(x=0; x<row.cells.length; x++){ if((from.row-y)*(y-to.row)>=0 && (from.col-x)*(x-to.col)>=0) row.cells.item(x).style.backgroundColor = "#ffdddd";//選択状態の色 else row.cells.item(x).style.backgroundColor = "transparent";//未選択状態の色 } } } //tableの中のcellの位置を取得する function getCellPos(table, cell){ var pos = new Object(); if(cell.nodeName == "TD"){ var x, y, cells; for(y=0; y<table.rows.length; y++){ row = table.rows.item(y); for(x=0; x<row.cells.length; x++){ if(row.cells.item(x) == cell){ pos.row = y; pos.col = x; return pos; } } } } return null; } </script> </head> <body><!-- Google Analytics Start --> <script type="text/javascript"> var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www."); document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E")); </script> <script type="text/javascript"> try { var pageTracker = _gat._getTracker("UA-9296140-1"); pageTracker._trackPageview(); } catch(err) {} </script> <!-- Google Analytics End --> <table onmousedown="mouseDown(this, event); return false;" onmouseup="mouseUp(this, event);" onmousemove="mouseMove(this, event); return false;"> </table> </body> </html>

  • 特定の列の<td>または<th>だけにスタイルを

    かけたいということがあります。 例えば、 ---------------------------------------------------------- <style type="text/css"> .tab1 th, .tab1 td { font-weight:normal; text-align:center; background:#fee; } .tab1 .row2 th { /* ----------------(1) */ background:#fff; } .tab1 .col2 th { /* ----------------(2) */ background:#ffff; } </style> <table class="tab1"> <col class="col1"> <col class="col2"> <col class="col3"> <tr class="row1"> <th>1</th> <th>2</th> <th>3</th> </tr> <tr class="row2"> <th>4</th> <td>5</td> <td>6</td> </tr> <tr class="row3"> <th>7</th> <td>8</td> <td>9</td> </tr> <table> ---------------------------------------------------------- だと、 1 2 3 4 5 6 7 8 9 の中の「4」は(1)により背景が白くなります。 しかし、(2)のようにしても「2」の背景は白くなりません。 <col>ってそういうものなのでしょうか? <td>または<th>にidをつけてスタイルをかけるしかないのでしょうか? よろしくお願いします。

    • ベストアンサー
    • HTML
  • WebDatabaseのlistから選択項目表示

    HTML5 Web Database でlistから選択した項目を詳細表示したい。詳細一覧detail_b()押下した際、listで選ばれているレコード内容を表示したい。色々試しているのですが・・・どこがおかしいかわかりません。 function load() で list.options[list.options.length] = new Option(row.val2, row.val, row.key1); 項目表示した場合、 function detail_b() で どのようなSELECT文を書けば listで選択された行を指定できるのですか? <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <script type="text/javascript"> var db = openDatabase("my_sample3", "", "Sample for my3", 1024*1024); db.transaction(function(tx) { tx.executeSql("create table if not exists storage (key1, val, val2)"); }); function load() { db.transaction(function(tx) { tx.executeSql("select * from storage", [], function(tx, rs) { var list = document.getElementById("list"); list.innerHTML = ""; var rows = rs.rows; for (var i = 0, n = rows.length; i < n; i++) { var row = rows.item(i); list.options[list.options.length] = new Option(row.val2, row.val, row.key1); } }); }); } function detail_b() { var list = document.getElementById("list"); if (list.selectedIndex < 0) { return; } var selected = list.options[list.selectedIndex].value; db.transaction(function(tx) { tx.executeSql("select * from storage where key1 = ?", [selected], function(tx, rs) { var rows = rs.rows; var row = rows.item(0); detail.innerHTML = ""; detail.options[detail.options.length] = new Option(row.val2, row.val, row.key1); }); }); } function remove() { 省略 } function add() { 省略 } </script> </head> <body onload="load()"> <h1></h1> <table border="0"> <tbody> <tr> <td colspan="2"><select id="list" size="5" style="width: 200px"></select></td> <td><button onclick="detail_b()">詳細一覧</button><BR><button onclick="remove()">削除</button></td> <td rowspan="4"><select id="detail" size="5" style="width: 400px"></select></td> </tr> <tr> <td><font face="Times New Roman">キー:</font></td> <td><input type="text" id="key1"></td> <td></td> </tr> <tr> <td><font face="Times New Roman">値:</font></td> <td><input type="text" id="value"></td> <td></td> <td></td> </tr> <tr> <td><font face="Times New Roman">値2:</font></td> <td><input type="text" id="value2"></td> <td><button onclick="add()">追加</button></td> </tr> </tbody> </table> </body> </htm>

    • ベストアンサー
    • HTML
  • セルにマウスが

    下記はセルにマウスが通過と離れた時に背景色を変えるPerlのコードです、通過したとき透明にしたいのですが、よろしくお願いします。 <SCRIPT LANGUAGE="JavaScript"> <!-- var evobj; function over(bg){ evobj=event.srcElement; if(evobj.tagName=="TR"||evobj.tagName=="TABLE"){ return } while(evobj.tagName!="TD"){ evobj=evobj.parentElement; } evobj.style.backgroundColor=bg; } function out(bg){ evobj.style.backgroundColor = bg; } //--> </SCRIPT> @bgcolor = qw(NAVY BLUE WHITE PINK); $bcolor = $bgcolor[int(rand($#bgcolor + 1))]; print "<TR onMouseOver=\"over(\'red\')\" onMouseOut=\"out(\'$bcolor\')\">

  • 要素の表示/非表示の実験

    をしてみました。 <input type="button" onclick="f()" value="push"/> <input type="button" onclick="g()" value="push"/> <table> <tr><td>a</td><td>b</td><td>c</td></tr> <tr id="x"><td>x</td><td>y</td><td>z</td></tr> <tr><td>u</td><td>v</td><td>w</td></tr> <tr id="y"><td>x</td><td>y</td><td>z</td></tr> <tr><td>a</td><td>b</td><td>c</td></tr> </table> <script> function f() { var x=document.getElementById('x').style.visibility; if(x=='hidden') document.getElementById('x').style.visibility='visible'; else document.getElementById('x').style.visibility='hidden'; } function g() { var x=document.getElementById('y').style.display; if(y!='none') document.getElementById('y').style.display='none'; else document.getElementById('y').style.display='block'; } </script> です。 最初のボタンは単に表示するかどうかだけで位置は消えた場所に詰められません。 次のボタンは消えるとその場所に他の要素が詰められます。しかし消えたものは次にボタンを押しても消えたままです。 消えた場所に要素が詰められしかも再表示できるようにするにはどうしたらいいのでしょうか?

  • 順番にセルの背景色をつけたい

    javascriptを使って セルの背景色一定の時間で順番に変える方法を調べています。 ボタンをクリックすると □□□□ ↓ ■□□□ ↓ □■□□ ↓ □□■□ ↓ □□□■ と変化するようなものを作成したいと考えております。 下記のソースでalertを出すと実現できるのですが、 alertをコメントアウトするとうまくいきません。 以上の点、アドバイス等お願いします。 <html> <head> <title></title> <script type="text/javascript"> function changeColor(){ var targetTable = document.getElementById('colorchange'); var targetTr = targetTable.rows[0]; var tdLen = targetTr.cells.length; for(var i = 0 ; i < tdLen ; i++ ){ if( i==0 ){ targetTr.cells[0].style.backgroundColor='red'; }else{ targetTr.cells[i-1].style.backgroundColor='white'; targetTr.cells[i].style.backgroundColor='red'; } wait( 300 ); //このalertを消すとうまくいかない alert('test'); } } function wait( timeWait ) { var timeStart = new Date().getTime(); var timeNow = new Date().getTime(); while( timeNow < (timeStart + timeWait ) ) { timeNow = new Date().getTime(); } } </script> </head> <body> <table border="1" id="colorchange"> <tr> <td>1111</td> <td>2222</td> <td>3333</td> <td>4444</td> </tr> </table> <button onClick="changeColor()">スタート</button> </body> </html>

  • Javascriptでテーブルタグの座標が知りたい(但し、マウスでなく)

    <html> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <title>JavaScriptテスト</title> <script type="text/javascript"> <!-- document.onmousedown = msDown //----------------------------------------------------------------------------- // マウスで座標を取得する //----------------------------------------------------------------------------- function msDown(){ var x = event.x; var y = event.y; alert('x=[' + x + '] y=[' + y + ']'); } // --> </script> </head> <body> テーブルタグの<TD>で左上側の画面上の位置の座標位置を取得したいです。 offsetLeftやoffsetTopでは、例えばテーブルタグの上側に<p>がある場合と無い場合でも同じ値でした。 正しく取得する方法はありますか? <hr> <table cellspacing="0" cellpadding="2" border="1" bgcolor="black"> <tbody> <tr> <td><img src="" width="100" height="100"></td> <td bgcolor="red">この赤のエリアの左上の座標が知りたい(マウスイベントで調べられるが、それを使わずに調べたい) </td> </tr> <tr> <td>456</td> <td><img src="" width="50" hright="50"></td> </tr> </tbody> </table> </body> </html>

  • セルの色を白くしたい。

    いつもお世話になっています。 以前こちらでjavascriptでまとめてセルの色を変えたいとお聞きした際答えていただき、それを元に下記のようなものを作りました。 色を変えるところはできたのですが、一度ついた色が消えないため、これを白に戻したいのですがどのようにすればよいでしょうか? 現状では、ボタンを押すとすべてクリアできれば満足ですが、いずれは細かく選択して白くしたいと思っています。 また、色を変える際、マウスオン、マウスアウトの際の追従がセルが多くなると遅延が発生してしまいますが、これを改善する方法はありますでしょうか? 質問がわかりにくいかもしれませんがよろしくお願いします。 <現状のスクリプト> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <HTML lang="ja"> <HEAD> <TITLE>スケジュールtest</TITLE> <STYLE> <!-- #colorchange{ border-collapse:collapse; } #colorchange td{ border:1px solid #000; width:20px; height:20px; background-color:#FFFFFF; } --> </STYLE> </HEAD> <BODY><SCRIPT> window.onload=function() { var t=document.getElementById("colorchange"); t.start=0; t.flg=false; var tds=t.getElementsByTagName("td"); var l=tds.length; var color=0; color = new Array(); var first=1; var selcolor="#ffc0c0"; var mousecolor="#ffc000"; var dbcolor="#ffff00" for(var i=0;i<l;i++) { tds[i].count=i; color[i]="#FFFFFF"; tds[i].onclick=function() { if(!t.flg) { t.start=this.count; } else { for(var j=0;j<l;j++) { if(first) { if(j>=t.start && j<=this.count || j<=t.start && j>=this.count) { tds[j].style.backgroundColor=selcolor; color[j]=tds[j].style.backgroundColor; } else { tds[j].style.backgroundColor="#FFFFFF"; color[j]="#FFFFFF"; } } else { if(j>=t.start && j<=this.count || j<=t.start && j>=this.count) { tds[j].style.backgroundColor=selcolor; } else { tds[j].style.backgroundColor=color[j]; } color[j]=tds[j].style.backgroundColor; } } t.start=0; first = 0; } t.flg=t.flg?false:true; } tds[i].onmouseover=function() { if(!t.flg) return false; for(var j=0;j<l;j++) { if(j>=t.start && j<=this.count || j<=t.start && j>=this.count) { if(color[j] == selcolor) { tds[j].style.backgroundColor=dbcolor; } else { tds[j].style.backgroundColor=mousecolor } } } } tds[i].onmouseout=function() { if(!t.flg) return false; for(var j=0;j<l;j++) { tds[j].style.backgroundColor=color[j]; } } } } </SCRIPT> <TABLE id="colorchange"> <tr> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> </tr> <tr> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> </tr> <tr> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> </tr> <tr> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> </tr> <tr> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> </tr> <tr> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> </tr> </table> </BODY> </HTML>

  • jquery input 要素取得

    失礼します。現在テーブルに記載されているテキストとinputの要素を取得して配列に格納したいのですが、input要素を取得できません ソースコードはこちらです。ご教授いただけますでしょうか。宜しくお願い致します。 <table id="tbl"> <tr> <td>fdfasdf</td> <td>hfadhfh</td> <td><input type="number" name="number" min='0' max="30" value=""></td> </tr> <tr> <td>hfdaha</td> <td>hfdsahsa</td> <td><input type="number" name="number" min='0' max="30" value=""></td> </tr> </tbody> </table> <script> var data = []; var tr = $("table tr");//全行を取得 for(var i=0, l=tr.length; i<l;i++ ){ //行数分回す var nk = 0; var cells = tr.eq(i).children();//1行目のtrの子要素は取得 for(var j=0, m=cells.length; j < m; j++ ){ //子要素分のcell分回す 0 < cell if(typeof data[i] == "undefined"){ //typeof(型判定) data[i] = []; //data[0] } if(nk < 2){ data[i][j] = cells.eq(j).text();//i行目j列の文字列を取得 data[0][0] ++nk; } data[i][j] = cells.eq(j).val(); } } </script>

専門家に質問してみよう