我在看 this question并看到了对 iPhone 游戏的引用,在该游戏中,您可以在屏幕上拖动,边走边选择字母。
我很想在 Javascript 中使用表格来实现这一点。因此,您将鼠标拖到每个单元格上,然后它们会突出显示。
我不确定最好的方法是什么,但我希望有人试一试。有人尝试过 here ,但实际上并没有用。
谢谢Cacoo对于性感的图表。这就像一个在线visio,非常好。检查一下 ;)
最佳答案
这是一个工作原型(prototype):http://jsfiddle.net/few5E/使用 jQuery 进行 DOM Hook ,但可以使用其他框架轻松实现。
更新:http://jsfiddle.net/Brv6J/略有不同的版本 - 突出显示的状态只会在您松开并再次单击时发生变化。
更新 2:http://jsfiddle.net/Brv6J/3/ - 绑定(bind) onselectstart 以便在 IE 中不选择文本。
一些相关事实:
- Hook 表格单元格的 mousedown 事件以跟踪实际点击。此事件已停止,因此文本选择受到阻碍。在 IE 中也绑定(bind) ontextselect 以获得相同的效果。
- 鼠标悬停事件将切换单元格的突出显示类
- mouseout 事件挂接到
文档
。这是为了确保它始终运行。如果 mouseup 事件卡在表格单元格上,则当您在表格外用鼠标松开鼠标键时,它不会触发。此状态在isMouseDown
中进行跟踪。
完整源码供引用:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title></title>
<style type="text/css" media="screen">
table td {
width:100px;
height:100px;
text-align:center;
vertical-align:middle;
background-color:#ccc;
}
table td.highlighted {
background-color:#999;
}
</style>
</head>
<body>
<table cellpadding="0" cellspacing="1" id="our_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>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript" charset="utf-8">
$(function () {
var isMouseDown = false;
$("#our_table 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
});
$(document)
.mouseup(function () {
isMouseDown = false;
});
});
</script>
</body>
</html>
关于javascript - 通过拖动选择表格中的单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2013902/