如何使用 <span> 和 JS 切换 <div> 标签隐藏和可见?

我正在建立一个带有搜索栏的网站,但是搜索内容太多,我需要一种方法让人们将其切换为隐藏


<div class="search">

<ul><a href="bashEmulator.html">Bash Shell Emulator</a></ul>

<ul><a href="bashShellUseHow.html">How to use bash shell </a></ul>


更重要的是。但是如何切换它被隐藏并用 JS 和显示<span>?非常感谢,环形游戏


萧十郎
浏览 121回答 3
3回答

慕仙森

您可以使用切换来添加和删除一个类,并且使用该类您可以隐藏搜索中的元素,这是一个示例:const searchElement = document.getElementById("search");const toggleElement = document.getElementById("toggle-visibility");toggleElement.addEventListener("click", toggleSearchVisibility);function toggleSearchVisibility() {&nbsp; searchElement.classList.toggle("hide-element")}.hide-element{&nbsp; display: none;}<div id="search">&nbsp; <ul><a href="bashEmulator.html">Bash Shell Emulator</a></ul>&nbsp; <ul><a href="bashShellUseHow.html">How to use bash shell </a></ul></div><span id="toggle-visibility">Click me!</span>

杨魅力

这是没有使用大库的 Vanilla Javascript<p>&nbsp; <a class="toggle" href="#example">Toggle Div</a></p><div&nbsp; id="example">&nbsp; <ul><a href="bashEmulator.html">Bash Shell Emulator</a></ul>&nbsp; <ul><a href="bashShellUseHow.html">How to use bash shell </a></ul></div><script>var show = function (elem) {&nbsp; &nbsp; elem.style.display = 'block';};var hide = function (elem) {&nbsp; &nbsp; elem.style.display = 'none';};var toggle = function (elem) {&nbsp; &nbsp; // If the element is visible, hide it&nbsp; &nbsp; if (window.getComputedStyle(elem).display === 'block') {&nbsp; &nbsp; &nbsp; &nbsp; hide(elem);&nbsp; &nbsp; &nbsp; &nbsp; return;&nbsp; &nbsp; }&nbsp; &nbsp; // Otherwise, show it&nbsp; &nbsp; show(elem);};// Listen for click eventsdocument.addEventListener('click', function (event) {&nbsp; &nbsp; // Make sure clicked element is our toggle&nbsp; &nbsp; if (!event.target.classList.contains('toggle')) return;&nbsp; &nbsp; // Prevent default link behavior&nbsp; &nbsp; event.preventDefault();&nbsp; &nbsp; // Get the content&nbsp; &nbsp; var content = document.querySelector(event.target.hash);&nbsp; &nbsp; if (!content) return;&nbsp; &nbsp; // Toggle the content&nbsp; &nbsp; toggle(content);}, false);</script>

回首忆惘然

我强烈建议您使用 JQuery 库。它超级简单,您只需将以下脚本添加到您的<head>标签中即可:<head><script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script></head>那么它会很简单:$("#clickedElementThatWillHide").click(function(){&nbsp; &nbsp; $("span").hide();&nbsp; });有关更多示例,请查看W3Schools
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript