我有一個彈出式選單,我試圖使用滑鼠懸停事件來切換它,但它似乎沒有按預期工作。我嘗試透過像這樣定位 div 來使用 CSS 懸停事件: .hero-list-block a:hover .flyout-menu
但是這沒有用。關於如何解決這個問題/改進這個問題有什麼建議嗎?謝謝
const flyoutLink = document.querySelector('.flyout-link'); const flyoutMenu = document.querySelector('.flyout-menu'); flyoutLink.addEventListener('mouseover', () => { flyoutMenu.classList.toggle('.flyout-menu-show'); })
.grid-hero-wrapper { grid-template-columns: 100px 1fr; gap: 15px; margin-top: 15px; display: grid; } .hero-categories-block { background: #fff; border: 1px solid #28282b; } .hero-categories-list { display: flex; flex-direction: column; padding: 5px 0; height: 100%; } .flyout-menu-show { opacity: 1; visibility: visible; } .flyout-menu { background: #fff; border: 1px solid #28282b; position: absolute; top: 0; width: 100%; height: 100%; opacity: 0; visibility: hidden; position: absolute; z-index: 999; } .hero-categories-list a { display: flex; align-items: center; flex-grow: 1; font-size: 0.75rem; height: 22px; color: #333; } .hero-slider-block { position: relative; }
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" /> <div class="grid-hero-wrapper"> <div class="hero-categories-block"> <div class="hero-categories-list"> <a href="#" class="flyout-link">Flyout</a> <a href="#" class="flyout-link">Flyout</a> </div> </div> <div class="hero-slider-block"> <div id="carouselExampleSlidesOnly" class="carousel slide" data-bs-ride="carousel"> <div class="carousel-inner"> <div class="carousel-item active hero-slider-img"> <img src="https://images.unsplash.com/photo-1507525428034-b723cf961d3e?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1173&q=80" class="d-block w-100"> </div> </div> </div> <div class="flyout-menu"> <h1>This is my flyout menu</h1> </div> </div> </div>
P粉1945410722024-04-04 12:56:25
由於 css 選擇器的特殊性,這不起作用。
.flyout-menu-show 選擇器在 .flyout-menu 選擇器之前聲明,並且它們具有相同的特異性。因此,只有最新的適用於您的元素。
改變
.flyout-menu-show { opacity: 1; visibility: visible; }
至
.flyout-menu.flyout-menu-show { opacity: 1; visibility: visible; }
這將創建一個具有更高特異性的選擇器,並且它將被正確應用:)。範例的工作代碼筆: https://codepen.io/aSH-uncover/pen/PoaboWo< /a>
可能也值得閱讀此頁面:https://developer. mozilla.org/en-US/docs/Web/CSS/Specificity