Jas*_*ard 5 html javascript css popup
我正在做一个学校项目,我们必须为一家餐厅做一个虚拟的静态菜单。到目前为止,我所做的是:当我单击一个按钮时,会出现一个弹出窗口,它包含在 class="menu" 的 div 中。问题是,我将所有菜单项存储在一个 JSON 文件中,因此我不知道菜单中有多少项。如果您看一下下面的代码,您会发现每个菜单项都包含在 < li > 标记中。现在,您还可以看到描述以显示开头:none; 财产。我想要做的是:使用 Javascript(我认为纯 HTML 和 CSS 不可能),我如何将描述的样式设置为显示:块;当“标题”类或“svg-container” 班级被称为?在任何一种情况下,当按下 svg 或标题时,svg 必须旋转 90 度,并在再次单击时返回 0 度。问题是我不知道如何获得已按下的确切项目的参考,以便我可以显示它的描述......
这是菜单目前外观的直观表示:
这就是为什么我需要将描述设置为 display: block;
<div class="menu">
<h2>Our Menu</h2>
<ul>
<li>
<label>
<div class="svg-container"> <img class="arrow" src="right-arrow.svg"/></div>
<span class="title">Fried Fish With Souce</span>
<div class="description" style="display: none;">
This is some internal content.This is some internal content.This is some internal content.
</div>
</label>
</li>
<li>
<label>
<div class="svg-container"> <img class="arrow" src="right-arrow.svg"/></div>
<span class="title">Spaghetti</span>
<div class="description" style="display: none;">
This is some internal content.This is some internal content.This is some internal content.
</div>
</label>
</li>
</ul>
</div>
Run Code Online (Sandbox Code Playgroud)
我尽力把问题解释清楚,有任何问题或不确定我都在这里回答。提前致谢!
编辑: 感谢大家的快速帮助,但在实现您的代码后,有一个小问题,看看当标题太长而不适合菜单 div 时会发生什么:
如您所见,标题完全在新行上移动,但它应该只将不适合的内容(不拆分单词,仅当有空格时)移动到新行上。
您需要做的就是处理该.menu级别的单击,然后使用 准确确定单击了菜单中的哪个项目[event.target][1]。这种方法利用称为“事件委托”的技术来利用事件冒泡。
// Set up event listener on the menu
document.querySelector(".menu").addEventListener("click", function(event){
// The actual item within the menu that was clicked is accessible
// through event.target. So, we'll find the nearest ancestor <li>
// of that, and then search for the .description element within that
// and change the style
event.target.closest("li").querySelector(".description").classList.remove("hidden");
});Run Code Online (Sandbox Code Playgroud)
.hidden { display:none; }Run Code Online (Sandbox Code Playgroud)
<div class="menu">
<h2>Our Menu</h2>
<ul>
<li>
<div class="svg-container">
<img class="arrow" src="right-arrow.svg"/>
<span class="title">Fried Fish With Souce</span>
</div>
<div class="description hidden">
This is some internal content.This is some internal content.This is some internal content.
</div>
</li>
<li>
<div class="svg-container">
<img class="arrow" src="right-arrow.svg"/>
<span class="title">Spaghetti</span>
</div>
<div class="description hidden">
This is some internal content.This is some internal content.This is some internal content.
</div>
</li>
</ul>
</div>Run Code Online (Sandbox Code Playgroud)
其他:
您没有正确使用该label元素。它旨在将标题与表单字段关联,而不是与常规 HTML 元素关联。
如果您希望菜单项的文本位于箭头旁边,则需要span将其位于前一个菜单项的内部div,而不是外部。
尽可能避免内联样式并使用 CSS 类。
如果您希望能够切换单击项目的可见性(显示/隐藏/显示/隐藏等),请使用.classList.toggle代替classList.remove。
| 归档时间: |
|
| 查看次数: |
49 次 |
| 最近记录: |