我有2个图例和2个div,我想做的是使用JavaScript 点击图例(signin_user),然后显示其内容,而其他隐藏。
当单击另一人时(signin_admin)显示,而其他人被隐藏
这通常称为标签样式登录表单
没有jquery
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<script>
document.addEventListener('DOMContentLoaded', () => {
document.querySelectorAll('legend', 'div').forEach(legend, div => {
div.addEventListener('onclick', () => {
// change color to selected legend
this.style.color = "#c8cace"
//show select div content
//make another legend white
//hide another div content
})
})
})
</script>
<style>
/* by default signin user is highlighted */
.user {
background-color: #c8cace;
}
</style>
<body>
<div id="user">
<legend class="user">signin user</legend>
<input type="text" name="user">
<input type="submit" id="submit-user">
</div>
<div id="admin">
<legend class="admin">signin admin</legend>
<input type="text" name="admin">
<input type="submit" id="submit-admin">
</div>
</body>
</html>
答案 0 :(得分:0)
您可以使用hide
属性classList
来切换类add/remove
:
.hide {
display: none;
}
document.addEventListener('DOMContentLoaded', function() {
document.querySelectorAll('legend').forEach(function(item) {
item.addEventListener('click', click_action);
});
});
function click_action(e) {
e.stopPropagation();
//Hide Other divs content
document.querySelectorAll('input').forEach(function(input) {
input.classList.add('hide');
});
//Show licked one content
event.target.parentNode.querySelectorAll('input').forEach(function(input) {
input.classList.remove('hide');
});
}
.user {
background-color: #c8cace;
}
.hide {
display: none;
}
<div id="user">
<legend class="user">signin user</legend>
<input type="text" name="user">
<input type="submit" id="submit-user">
</div>
<div id="admin">
<legend class="admin">signin admin</legend>
<input type="text" name="admin" class="hide">
<input type="submit" id="submit-admin" class="hide">
</div>