6

是否有一个 Javascript 包可以通过单击它们并使用ShiftCtrl键使表格行可选择/突出显示?

我正在寻找与 iTunes 或其他音乐播放器相同的功能,它允许通过单击行来突出显示一首歌曲,或者通过按住 shift 或 control 并单击来突出显示多首歌曲。

4

2 回答 2

10

你可以在没有插件的情况下做到这一点!

此示例通过按住, (对于 MacOS 用户)或键盘键并单击来实现highlights一个或多个。rowCtrlcmd Shift

我会建议避免使用插件来处理简单的事情。您会看到,对于您需要实现的目标,这并不是很多代码。

现场演示:http: //jsfiddle.net/oscarj24/ctLm8/2/


HTML:

假设我有下表(您将与行交互)。

<table border="1">
    <tr>
        <th>Id</th>
        <th>Name</th>
        <th>Age</th>
        <th>Salary</th>
    </tr>
    <tr>
        <td>1</td>
        <td>Luis</td>
        <td>28</td>
        <td>$100,000</td>
    </tr>
    <tr>
        <td>2</td>
        <td>Oscar</td>
        <td>29</td>
        <td>$90,000</td>
    </tr>
    <tr>
        <td>3</td>
        <td>Daniel</td>
        <td>18</td>
        <td>$50,000</td>
    </tr>
</table>

CSS:

现在我将创建一些在导航时使用CSS仅用于样式,您可以将其删除)和另一个到.default cursortable highlightrow

tr { cursor: default; }
.highlight { background: yellow; }

jQuery:

这是您需要的所有代码,请阅读评论。

$(function() {

    /* Get all rows from your 'table' but not the first one 
     * that includes headers. */
    var rows = $('tr').not(':first');

    /* Create 'click' event handler for rows */
    rows.on('click', function(e) {

        /* Get current row */
        var row = $(this);

        /* Check if 'Ctrl', 'cmd' or 'Shift' keyboard key was pressed
         * 'Ctrl' => is represented by 'e.ctrlKey' or 'e.metaKey'
         * 'Shift' => is represented by 'e.shiftKey' */
        if ((e.ctrlKey || e.metaKey) || e.shiftKey) {
            /* If pressed highlight the other row that was clicked */
            row.addClass('highlight');
        } else {
            /* Otherwise just highlight one row and clean others */
            rows.removeClass('highlight');
            row.addClass('highlight');
        }

    });

    /* This 'event' is used just to avoid that the table text 
     * gets selected (just for styling). 
     * For example, when pressing 'Shift' keyboard key and clicking 
     * (without this 'event') the text of the 'table' will be selected.
     * You can remove it if you want, I just tested this in 
     * Chrome v30.0.1599.69 */
    $(document).bind('selectstart dragstart', function(e) { 
        e.preventDefault(); return false; 
    });

});

最后,如果你坚持要创建一个插件,你可以看看这个网站并根据你的需要定制代码。

http://learn.jquery.com/plugins/basic-plugin-creation/

其他功能仅取决于您,我只是回答了您在问题中的要求:-) 希望这会有所帮助。

于 2013-10-21T00:20:42.720 回答
4

您可以使用 jQuery UI selectable

您可以选择多个项目持有Ctrl,或者您可以单击一个项目并拖动。

API 参考

JS Bin 示例

于 2013-10-20T22:57:20.060 回答