在单元格悬停时显示/隐藏DIV(javascript)

Display/Hide DIVs on tablecell hover (javascript)

本文关键字:DIV javascript 隐藏 单元格 悬停 显示      更新时间:2023-09-26

我构建了一个包含大约20个单元格的表。在表旁边,我想显示一个带有描述的<div>,它应该在悬停或单击时显示。网络上有很多可用的解决方案,但没有一个真正适合。

我已经知道我确实需要JavaScript,所以我有了我的表格单元格

<td class="des1">Content</td>

<div id="des1">my Description1</div>

我在单元格中添加了一个类,因为某些描述是由多个单元格调用的

因此,我需要一个JavaScript函数来在悬停/单击类"des1"的所有单元格时显示div"des1",并隐藏之前显示的所有其他描述。这就是我的问题。

我的所有描述都被包装在其他div中,所以我可以在包装中隐藏所有div,然后显示正确的描述。最好的方法是什么(事件处理?内联?)我应该在Addition中使用CSS吗?

我在Javascript方面没有太多经验,所以如果有任何帮助或提示,我将不胜感激。

您想要实现的目标有两个基本部分:

  1. 事件处理(对用户悬停/单击做出响应)
  2. DOM操作(更改描述)

我强烈建议使用jQuery库来帮助实现这两个功能。

使用jQuery,您可以轻松地"绑定"一个事件处理程序,该事件处理程序将对单击或悬停在其上的单元格做出响应。例如:

$('.des1').click(function() {
    // Whatever you put here will be triggered when the user clicks on an element
    // with class "des1"
});

悬停处理程序是类似的,尽管稍微复杂一些,因为它允许您指定用户开始悬停和停止悬停时发生的情况:

$('.des1').hover(function() {
    // Whatever you put here will be triggered when the user hovers over an element
    // with class "des1"
}, function() {
    // Whatever you put here will be triggered when the user stops hovering over an 
    // element with class "des1"
});

在处理程序中,您需要添加逻辑来修改具有适当ID的元素的文本,可以使用jQuery的text方法:

$('#des1').text('My Description #1');

将两者结合起来,并在它们之间共享一个函数,您可以得到以下内容:

var showDescription1 = function() {
    // Whatever you put here will be triggered when the user clicks on an element
    // with class "des1"
};
$('.des1').click(showDescription1)
$('.des1').hover(showDescription1, function() {
     // if you want to change the description back when the user stops hovering, you'd
     // add that logic here
});
<style>
    div.des {
        display: none;
    }
</style>
<table>
    <tr>
        <td class="des1">Content 1</td>
    </tr>
    <tr>
        <td class="des2">Content 2</td>
    </tr>
    <tr>
        <td class="des3">Content 3</td>
    </tr>
</table>
<div id="des1" class="des">Description 1</div>
<div id="des2" class="des">Description 2</div>
<div id="des3" class="des">Description 3</div>
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
<script>
    $('table td').on('click', function() {
        var $des = $('#' + $(this).attr('class')),
            visible = $des.hasClass('active');
        $('div').hide();
        if(visible) {
            return;
        }
        $des
            .addClass('active')
            .show();
    });
</script>