[英]Hide a div when another is visible
當顯示菜單覆蓋時,我試圖隱藏一個帶有類.search-container-inner input
的搜索框。 它有一個.overlay.style-light-bg
。
我無法讓它與 CSS 一起使用,因為它們沒有直接關系,並且搜索框位於 HTML 中的疊加層之前。
我嘗試從以前的帖子中編輯此解決方案:
// Show an element
var show = function (elem) {
elem.style.display = 'block';
};
// Hide an element
var hide = function (elem) {
elem.style.display = 'none';
};
// Toggle element visibility
var toggle = function (elem) {
// If the element is visible, hide it
if (window.getComputedStyle(elem).display === 'block') {
hide(elem);
return;
}
// Otherwise, show it
show(elem);
};
但無濟於事。
這將是:
var toggle = function (elem) {
if(!elem.classList.contains(class);)
elem.classList.toggle('hidden');
}
我不知道如何調用或呈現疊加層,但您可以檢查該類是否存在,然后將display
更改為搜索框,如下所示:
var searchInput = document.querySelector(".search-container-inner input");
if (document.querySelector(".overlay.style-light-bg")) { // check if exists
searchInput.style.display = "none";
} else {
searchInput.style.display = "block";
}
它會運行一次,但您也可以將其包裝成一個函數,以便隨時調用。
由於您已經為編寫show
hide
和toggle
功能的代碼奠定了基礎,剩下的就是根據您的要求調用它們。
var overlay = document.querySelector('.overlay.style-light-bg');
var search = document.querySelector('.search-container-inner input');
if (window.getComputedStyle(overlay).display === 'block') {
hide(search);
return;
}
現在,在顯示疊加層時調用上面的代碼
您可以使用MutationObserver來實現所需的行為。 它提供了監視對 DOM 樹所做的特定更改並調用回調函數來處理更改的能力。 它具有回到 IE 11 的瀏覽器支持。
這是包含魔術doSomething()
函數的骨架代碼。
function doSomething() {
var overlay = window.getComputedStyle(document.querySelector('.overlay.style-light-bg')).display
var searchInput = document.querySelector('.search-container-inner input')
searchInput.style.display = (overlay == 'block') ? 'none' : 'block'
}
// The following code uses MutationObserver to call `doSomething()` when needed
// Handle to the DOM element that will be observed
var overlayNode = document.querySelector('.overlay.style-light-bg')
// Configure the observer to watch for changes to the element's attributes only
var observerConfig = { attributes: true }
// Callback function to execute when mutations are observed
var observerCallback = function(mutationsList, observer) {
for (var mutation of mutationsList) {
if (mutation.type == 'attributes') {
console.log('The ' + mutation.attributeName + ' attribute was modified.')
if (mutation.attributeName == 'style' || mutation.attributeName == 'class') {
// handle the mutation of the overlay element's style or class list
doSomething()
}
}
}
}
// Create a `MutationObserver` instance linked to the `observerCallback` function
var overlayObserver = new MutationObserver(observerCallback);
// Start observing the overlay node for configured mutations
overlayObserver.observe(overlayNode, observerConfig);
根據疊加的變化方式,控制台輸出將顯示:
The style attribute was modified.
或者
The class attribute was modified.
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.