在单元格悬停时显示/隐藏DIV(javascript)
Display/Hide DIVs on tablecell hover (javascript)
我构建了一个包含大约20个单元格的表。在表旁边,我想显示一个带有描述的<div>
,它应该在悬停或单击时显示。网络上有很多可用的解决方案,但没有一个真正适合。
我已经知道我确实需要JavaScript,所以我有了我的表格单元格
<td class="des1">Content</td>
和
<div id="des1">my Description1</div>
我在单元格中添加了一个类,因为某些描述是由多个单元格调用的
因此,我需要一个JavaScript函数来在悬停/单击类"des1"的所有单元格时显示div"des1",并隐藏之前显示的所有其他描述。这就是我的问题。
我的所有描述都被包装在其他div中,所以我可以在包装中隐藏所有div,然后显示正确的描述。最好的方法是什么(事件处理?内联?)我应该在Addition中使用CSS吗?
我在Javascript方面没有太多经验,所以如果有任何帮助或提示,我将不胜感激。
您想要实现的目标有两个基本部分:
- 事件处理(对用户悬停/单击做出响应)
- 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>
相关文章:
- 使用JavaScript动态插入DIV的成本有多高
- 绝对定位不适用于Javascript DIV
- 当DIV中的文本高亮显示时,如何获得DIV中Span的值?(Javascript)
- 用于Dynamic Div'的Javascript数学函数;s风格
- DIV怎么能像Javascript中的另一个元素一样工作呢
- 多个DIV上的Javascript
- Javascript关键字搜索子类Div值
- JavaScript on点击更新Div
- 更改CSS以允许使用Javascript控制DIV位置
- 如何使用Javascript替换和隐藏Div内容
- 从Div创建图像,并使用Javascript和ASP.net将其保存到服务器
- Trouble overlaying one div with another with JavaScript &
- JavaScript/jQuery:显示DIV,直到用户停止在Textbox中键入
- 当Div可见时使用Javascript
- DIV - JavaScript 中的相对鼠标坐标
- 默认加载DIV Javascript
- 在DIV Javascript中添加AutoScroll
- 在单元格悬停时显示/隐藏DIV(javascript)
- 从DIV JavaScript中的几个元素更改ID和NAME
- Toggle Div Javascript