也许这可以通过某种方式进行优化,但我只在 Chrome 中对其进行了测试,但我认为它也可以在其他浏览器中使用。不需要 jQuery UI,它是手工制作的 ;)
$(function() {
var selectableLi = $('#selectable li');
selectableLi.mousedown(function(){
var startIndex, endIndex, mouseUpOnLi = false;
// When dragging starts, remove classes active and hover
selectableLi.removeClass('active hover');
// Give the element where dragging starts a class
$(this).addClass('active');
// Save the start index
startIndex = $(this).index();
// Bind mouse up event
selectableLi.bind('mouseup', function(){
// Mouse up is on a li-element
mouseUpOnLi = true;
$(this).addClass('active');
// Remove the events for mouseup, mouseover and mouseout
selectableLi.unbind('mouseup mouseover mouseout');
// Store the end index
endIndex = $(this).index();
// Swap values if endIndex < startindex
if(endIndex < startIndex){
var tmp = startIndex;
startIndex = endIndex;
endIndex = tmp;
}
// Give the selected elements a colour
for(i=startIndex; i<=endIndex; i++){
$(selectableLi[i]).addClass('active');
}
}).bind('mouseover', function(){
// Give elements a hover class when hovering
$(this).addClass('hover');
}).bind('mouseout', function(){
// Remove the hover class when mouse moves out the li
$(this).removeClass('hover');
});
$(document).bind('mouseup', function(e){
// When mouse up is outside a li-element
if(!mouseUpOnLi){
selectableLi.removeClass('active');
}
$(this).unbind('mouseup');
});
}).attr("unselectable","on").css("MozUserSelect","none").bind("selectstart",function(){return false});
});
我在网上有一个例子。请注意,选择时项目没有背景颜色;我认为这将提供更好的性能。
更新 -示例 2
我更新了它,以便在选择时可以看到选择:
var selectableLi;
function colourSelected(a, b, Class){
selectableLi.removeClass(Class);
// Swap values if a > b
if(a > b){
var tmp = a;
a = b;
b = tmp;
}
// Give the selected elements a colour
for(i=a; i<=b; i++){
$(selectableLi[i]).addClass(Class);
}
}
$(function() {
selectableLi = $('#selectable li');
selectableLi.mousedown(function(){
var startIndex, endIndex, mouseUpOnLi = false;
// When dragging starts, remove classes active and hover
selectableLi.removeClass('active hover');
// Give the element where dragging starts a class
$(this).addClass('active');
// Save the start index
startIndex = $(this).index();
// Bind mouse up event
selectableLi.bind('mouseup', function(){
// Mouse up is on a li-element
mouseUpOnLi = true;
$(this).addClass('active');
// Remove the events for mouseup, mouseover and mouseout
selectableLi.unbind('mouseup mouseover mouseout');
colourSelected(startIndex, $(this).index(), 'active');
}).bind('mouseover mouseout', function(){
// Give elements a hover class when hovering
colourSelected(startIndex, $(this).index(), 'hover');
});
$(document).bind('mouseup', function(e){
// When mouse up is outside a li-element
if(!mouseUpOnLi){
selectableLi.removeClass('active hover');
}
$(this).unbind('mouseup');
selectableLi.unbind('mouseover mouseout');
});
}).attr("unselectable","on").css("MozUserSelect","none").bind("selectstart",function(){return false});
});
同样,也许可以以某种方式优化此代码以提高性能。