css - 使用 HTML、CSS、Jquery 在单击 div 时启用禁用按钮?
问题描述
对于我遇到的禁用/启用按钮问题,我将不胜感激。我正在学习 Jquery,所以解决这个问题对我来说将是一个很大的教训。我制作了一个使用 div 类的用户列表:
<div class="userList">
<div class="user">Tom</div>
<div class="user">Ben</div>
<div class="user">George</div>
<div class="user">Tony</div>
</div>
在用户列表下,我有四个按钮:
<div class="actions">
<button id="add" disabled="disabled">Add</button>
<button id="block" disabled="disabled">Block</button>
<button id="message" disabled="disabled">Message</button>
<button id="exit">Exit</button>
</div>
如您所见,默认情况下禁用 4 个按钮中的 3 个。我想要做的是单击一个用户,该用户将以背景颜色突出显示该用户,同时启用 3 个禁用的按钮。我还想按 ID 定位各个按钮。一旦我单击另一个用户名或“userList”div 之外,只有我单击的用户名会更改背景颜色并变回原始颜色。
这是完整的 HTML 代码:
<div id="wrapper">
<div class="userList">
<div class="user">Tom</div>
<div class="user">Ben</div>
<div class="user">George</div>
<div class="user">Tony</div>
</div>
<div class="actions">
<button id="add" disabled="disabled">Add</button>
<button id="block" disabled="disabled">Block</button>
<button id="message" disabled="disabled">Message</button>
<button id="exit">Exit</button>
</div>
</div>
这是CSS代码:
@charset "utf-8";
* {
padding:0;
margin:0;
font-family:Arial, Helvetica, sans-serif;
}
#wrapper {
width:300px;
min-height:100px;
background-color:#ddd;
margin:0 auto;
padding:20px;
}
.userList {
border:1px solid #aaa;
padding:20px;
margin-bottom:20px;
}
.user {
background:#eee;
line-height:28px;
border:1px solid #aaa;
margin-bottom:5px;
padding-left:10px;
}
.user:hover {
background:#06F;
color:#fff;
border:1px solid #000;
}
.actions {}
我希望有人可以帮助我!这将教会我,并希望更多的人学到很多。
解决方案
假设我正确理解了您的问题,那么可能会这样做:
$('.user').click(function(event){
removeHighlight();
$(event.target).addClass('highlight'); // Highlight selected item
$('.btn-action').attr('disabled', false); // Enable action buttons
});
$(document).click(function(event) {
// If clicked element does not have the class 'userList'
// and does not have a parent element with a class 'userList'
if(!$(event.target).hasClass('userList') && !$(event.target).parents('.userList').length) {
removeHighlight();
$('.btn-action').attr('disabled', true); // Disable action buttons
}
});
function removeHighlight() {
$('.user').each(function() { // Remove highlight class for any previously selected item
$(this).removeClass('highlight');
});
}
将此添加到您的样式中:
.user.highlight {
background:#06F;
color:#fff;
border:1px solid #000;
}
btn-action
并为您的按钮添加类。
推荐阅读
- python - Matplotlib:ListedColormap 不映射颜色
- python - Flask - 400 错误请求
- javascript - 基于键的降序对象
- excel - VBA 代码将数据从第 2 行复制到一个工作表上的最后一行数据并粘贴到另一个工作表的第一个空行
- .net - 将 1 中的两个对象链接到 * 关联时,无法在种子方法中的对象中插入重复键
- sql - 子查询的返回值
- python - 试图刮,让 [] 回来
- python - 我如何捕捉 Python PyQt5 QTreeWidget 按回车键?
- python - 在不使用索引的情况下删除匹配值之后的所有列
- sql - 从 SQL 查询到 MkDir 的 VBA 循环