描述
我创建了一个 12x12 的网格。每个单元格的 id 为“_1”、“_2”等。 例如。
<span id="_1">L</span>
<span id="_2">B</span>
我使用以下代码在拖动时突出显示。
function initWordSearch() {
var active = false;
$("#game-section span").mousedown(function(ev) {
active = true;
$(".highlightE").removeClass("highlightE"); // clear previous selection
ev.preventDefault(); // this prevents text selection from happening
$(this).addClass("highlightE");
});
$("#game-section span").mousemove(function(ev) {
if (active) {
console.log($(this).text());
$(this).addClass("highlightE");
}
});
$(document).mouseup(function(ev) {
active = false;
});
}
$(document).ready(function(e) {
initWordSearch();
});
实现目标
目前,无论我将鼠标移到哪里,该框都会被选中。 我想仅从左到右水平选择框或从上到下垂直选择框。
这是jsfiddle link了解目前的进展。
提前致谢
最佳答案
我会考虑设置一些全局变量来保存目标跨度的位置,然后比较它们:
更多解释请参见 JS 注释
// Set global variables for comparisons
var active, start, startX, startY, axis;
$("#game-section span").mousedown(function(ev) {
start = $(this)
active = true;
$(".highlightE").removeClass("highlightE"); // clear previous selection
ev.preventDefault(); // this prevents text selection from happening
start.addClass("highlightE");
// Set global variables
var position = start.position()
startX = position.left;
startY = position.top;
});
$("#game-section span").mousemove(function(ev) {
// Get direction of the first highlighted span to compare
if(!$(this).hasClass('highlightE') && active) {
var position = $(this).position();
var x = position.left;
var y = position.top;
// Only decide which way the highlights should go on the first one highlighted
if(!axis) {
x === startX ? axis = 'y' : axis = 'x';
}
// If axis is equal to y, it should go sideways
if(axis === 'y' && x === startX && y > startY) {
$(this).addClass("highlightE");
}
// If its x, it should go up and down
if(axis === 'x' && y === startY && x > startX) {
$(this).addClass("highlightE");
}
}
});
关于javascript - jQuery 仅水平或垂直选择单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44511207/