<!-- チェックボックスグループ -->
<div>
<input type="checkbox" id="option1" name="options" value="option1" />
<label for="option1">オプション</label>
<input type="checkbox" id="option2" name="options" value="option2" />
<label for="option2">オプション</label>
<input type="checkbox" id="option3" name="options" value="option3" />
<label for="option3">オプション3</label>
<input type="checkbox" id="option4" name="options" value="option4" />
<label for="option4">オプション</label>
<input type="checkbox" id="option5" name="options" value="option5" />
<label for="option5">オプション</label>
</div>
<!-- ボタン --><!-- ボタン -->
<div>
<button name="button1">ボタン1</button>
<div class="button2-wrapper">
<button name="button2">ボタン2</button>
<span class="tooltip"></span>
</div>
</div>
<style>
button {
transition: opacity 0.3s;
}
button[disabled] {
opacity: 0.5;
cursor: not-allowed;
}
.button2-wrapper {
position: relative;
display: inline-block;
}
.tooltip {
opacity: 0;
visibility: hidden;
max-height: 0;
padding: 0;
overflow: hidden;
background-color: #333;
color: #fff;
text-align: center;
border-radius: 4px;
position: absolute;
z-index: 1;
bottom: 100%;
left: 50%;
transform: translateX(-50%);
white-space: nowrap;
}
/* button2にホバーしたときだけツールチップを表示 */
button[name="button1"]:enabled
+ .button2-wrapper
button[name="button2"]:disabled:hover
+ .tooltip {
visibility: visible;
opacity: 1;
max-height: 1000px; /* 適切な高さに設定 */
padding: 0.25em 0.5em;
}
</style>
<script>
// チェックボックスの要素を取得
const checkboxes = document.querySelectorAll('input[type="checkbox"]');
// ボタンの要素を取得
const button1 = document.querySelector('button[name="button1"]');
const button2 = document.querySelector('button[name="button2"]');
const tooltip = document.querySelector(".tooltip");
// チェックボックスの変更イベントを監視
checkboxes.forEach((checkbox) => {
checkbox.addEventListener("change", toggleButtons);
});
// ボタンの有効/無効を切り替える関数
function toggleButtons() {
const checkedCheckboxes = Array.from(checkboxes).filter(
(checkbox) => checkbox.checked
);
const checkedTexts = checkedCheckboxes.map(
(checkbox) => checkbox.nextElementSibling.textContent
);
const areAllTextsTheSame = checkedTexts.every(
(text) => text === checkedTexts[0]
);
button1.disabled = !checkedCheckboxes.length;
button2.disabled = !areAllTextsTheSame || !checkedCheckboxes.length;
// ツールチップのテキストを設定
tooltip.textContent = button2.disabled ? "button2は無効です" : "";
}
toggleButtons();
</script>
Register as a new user and use Qiita more conveniently
- You get articles that match your needs
- You can efficiently read back useful information
- You can use dark theme