HTML 表可选行 Javascript 包

HTML table selectable rows Javascript package

本文关键字:Javascript HTML      更新时间:2023-09-26

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

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

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

此示例通过按住 Ctrlcmd(适用于 MacOS 用户)Shift 键盘键并单击来highlights一个或多个row

我建议避免使用简单事物的插件。您将看到,对于您需要实现的目标,这不是要实现的大量代码。

现场演示: 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以在导航table时使用default cursor(仅用于样式,您可以将其删除),另一个用于highlight row

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

j查询:

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

$(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/

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

你可以使用 jQuery UI 可选。

您可以按住 Ctrl 选择多个 itens,也可以单击一个项目并拖动。

API 参考。

JS垃圾桶示例。