<div id="container">
<div>
<p class="selectable">fj g fjdhgdfkgd fj 1</p>
<p class="selectable">fj g fjdhgdfkgd fj 2</p>
<p class="selectable">fj g fjdhgdfkgd fj3</p>
</div>
<div>
<p class="selectable">fj g fjdhgdfkgd fj 4</p>
<p class="selectable">fj g fjdhgdfkgd fj 5</p>
<p class="selectable">fj g fjdhgdfkgd fj 6</p>
</div>
<div>
<p class="selectable">fj g fjdhgdfkgd fj 7</p>
<p class="selectable">fj g fjdhgdfkgd fj 8</p>
<p class="selectable">fj g fjdhgdfkgd fj 9</p>
</div>
<div>
<p class="selectable">fj g fjdhgdfkgd fj 10</p>
<p class="selectable">fj g fjdhgdfkgd fj 11</p>
<p class="selectable">fj g fjdhgdfkgd fj 12</p>
</div>
</div>
在上面的结构中,我想使用shiftKey + click来选择多个
。
我得到的this与我想要的相似,但没有帮助。所以你也可以看看这个
答案 0 :(得分:1)
试试这个:
<强> JS:强>
$(document).ready(function () {
$(document).on("click", ".selectable", function (e) {
var elem = $(this);
if (e.shiftKey) {
elem.toggleClass("selected");
}
});
});
<强> CSS:强>
.selected {
font-weight:bold; //Or any effect to distinguish it
}
演示:http://jsfiddle.net/GCu2D/656/
这与参考小提琴之间的区别在于,当您再次单击所选项目时,该项目将被取消选择。
获取所选项目:
$(".selected"); //this will give you an array of selected items.
答案 1 :(得分:1)
我已根据您的要求使其发挥作用。
<div class="container">
<div id="div1">
<p class="selectable">lorem</p>
<p class="selectable">ipsum</p>
</div>
<div id="div2">
<p class="selectable">dolor</p>
<p class="selectable">sit</p>
<p class="selectable">amet</p>
</div>
</div>
<script>
var $lastSelected = [],
container = $('.container'),
collection = $('.selectable');
container.on('click', '.selectable', function(e) {
var that = $(this),
$selected,
direction;
if (e.shiftKey){
if ($lastSelected.length > 0) {
if(that[0] == $lastSelected[0]) {
// The user has clicked on the same item, so do nothing.
// Remember, `that` is our event target
// You could also make this deselect everything except for this item
if(that.hasClass('selected')) that.removeClass('selected');
return false;
}
if(that.hasClass('selected')) that.removeClass('selected');
else that.addClass('selected');
$lastSelected = that;
} else {
$lastSelected = that;
that.addClass('lastSelected');
that.addClass('selected');
}
} else {
// Not a shift select, so we'll just mark the target item
$lastSelected = that;
collection.removeClass('lastSelected selected');
that.addClass('lastSelected selected');
}
});
</script>