我正在添加这段代码以将 ID
附加到 li
元素内的类 (li.search
)。
document.querySelector('li.search').id = 'ControlOverlay';
它适用于我的一些网站,但在最近的安装中,它没有将 ID
附加到 class
。
当我在 w3schools.com
上测试时,我的实现有效,但在我的网站上却没有...
有什么想法可能是错误的吗?
我是不是忘记引用任何库了?
这是我的实现:
<!DOCTYPE html>
<html>
<style>
#overlays {position:fixed;top:0;left:0;right:0;bottom:0;z-index:0;background:rgba(110, 173, 238,.9);}
.standby2 {display:none;}
ul {list-style:none;}
</style>
<body>
<ul class="menu">
<li class="search"><a aria-label="Open" href="#"><span class="gp-icon icon-search"><svg viewBox="0 0 512 512" aria-hidden="true" role="img" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="1em" height="1em">
<path fill-rule="evenodd" clip-rule="evenodd" d="M208 48c-88.366 0-160 71.634-160 160s71.634 160 160 160 160-71.634 160-160S296.366 48 208 48zM0 208C0 93.125 93.125 0 208 0s208 93.125 208 208c0 48.741-16.765 93.566-44.843 129.024l133.826 134.018c9.366 9.379 9.355 24.575-.025 33.941-9.379 9.366-24.575 9.355-33.941-.025L337.238 370.987C301.747 399.167 256.839 416 208 416 93.125 416 0 322.875 0 208z"></path>
</svg><svg viewBox="0 0 512 512" aria-hidden="true" role="img" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="1em" height="1em">
<path d="M71.029 71.029c9.373-9.372 24.569-9.372 33.942 0L256 222.059l151.029-151.03c9.373-9.372 24.569-9.372 33.942 0 9.372 9.373 9.372 24.569 0 33.942L289.941 256l151.03 151.029c9.372 9.373 9.372 24.569 0 33.942-9.373 9.372-24.569 9.372-33.942 0L256 289.941l-151.029 151.03c-9.373 9.372-24.569 9.372-33.942 0-9.372-9.373-9.372-24.569 0-33.942L222.059 256 71.029 104.971c-9.372-9.373-9.372-24.569 0-33.942z"></path>
</svg></span></a></li> </ul>
<script>
document.querySelector('li.search').id = 'ControlOverlay';
document.getElementById("ControlOverlay").setAttribute("onclick", "ShowOverlay();");
function ShowOverlay(){document.getElementById("overlays").classList.toggle("standby2")}
</script>
这是一个 jsfiddle
最佳答案
问题出在document.getElementById("overlay")
您的 HTML 中没有 ID 为 overlay
的元素。
我也会编辑
document.getElementById("ControlSearchOverlay").setAttribute("onclick", "ShowHideOverlay();");
function ShowHideOverlay(){
document.getElementById("overlay").classList.toggle("standby")
}
到:
document.getElementById("ControlSearchOverlay").onclick = function() {
document.getElementById("overlay").classList.toggle("standby")
}
正如 user4642212 提到的,最好使用 addEventListener https://developer.mozilla.org/de/docs/Web/API/EventTarget/addEventListener
document.getElementById("ControlSearchOverlay").addEventListener('click', function() {
document.getElementById("overlay").classList.toggle("standby")
})
关于javascript - 文档查询选择器实现的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62556487/