<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script> <style> .menu{ width: 120px; margin: 20px auto; } span{ line-height: 50px; font-size: 20px; margin-left: 36px; } .list{ width: 100px; line-height: 18px; border: 2px solid #888; padding: 0 10px; display: none; } </style> </head> <body> <div class="menu"> <span>菜单</span> <div class="list"> <p>新建课堂</p> <p>新建实训</p> <p>新建实训路径</p> <p>新建项目</p> </div> </div> <script> $(function(){ //-------------- Begin ---------------- //-------------- End -------------------- }) </script> </body> </html>
时间: 2024-02-27 12:53:16 浏览: 50
这是一个基本的 HTML 页面,包含一个菜单容器和一个菜单内容容器。当点击菜单时,菜单内容会展开或收起。下面是实现这个效果的 jQuery 代码:
```javascript
$(function() {
$(".menu > span").click(function() {
$(this).siblings(".list").slideToggle();
});
});
```
解释一下:
- `$()` 是 jQuery 的选择器,可以选中 HTML 元素。
- `$(".menu > span")` 是选中菜单容器中的标题元素。
- `.click()` 方法是当元素被点击时执行的函数。
- `$(this)` 是指当前被点击的元素。
- `.siblings(".list")` 是选中当前被点击元素的兄弟元素中的菜单内容容器。
- `.slideToggle()` 方法是执行展开或收起动画,如果菜单内容容器是展开状态,则会收起,反之亦然。
这样,当点击菜单时,菜单内容会展开或收起。
相关问题
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <script src="/jquery-3.6.3.min.js"> $("#11").click(function (){ alert("haha"); }) </script> <button id="11">haha</button> </body> </html>该代码为什么不弹出警示框
该代码没有在文档加载完成后执行JavaScript代码,因此jQuery代码无法生效。在引入jQuery库的`<script>`标签中,应该只引入jQuery库文件,而不应该将JavaScript代码写在里面。
正确的写法是,将jQuery代码放在`<script>`标签外面,并将代码放在文档就绪函数中,如下所示:
```
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<button id="11">haha</button>
<script src="/jquery-3.6.3.min.js"></script>
<script>
$(document).ready(function(){
$("#11").click(function (){
alert("haha");
});
});
</script>
</body>
</html>
```
这样,在网页加载完成后,jQuery代码才会生效,点击按钮时才会弹出警示框。
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <style> #father { width: 300px; height: 300px; background-color: pink; margin: 100 auto; } </style> </head> <body> <div id="father"> <div id="son"></div> <div></div> <div></div> </div> <script> let i = document.querySelector(".father") console.log(i); </script> </body> </html>
根据你提供的代码,你的 HTML 中的 `div` 元素的 `id` 属性为 `father`,而不是 `class` 属性。因此,你应该使用 `querySelector("#father")` 来选择 `id` 为 `father` 的元素,而不是 `querySelector(".father")`。
以下是修改后的代码:
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
#father {
width: 300px;
height: 300px;
background-color: pink;
margin: 100 auto;
}
</style>
</head>
<body>
<div id="father">
<div id="son"></div>
<div></div>
<div></div>
</div>
<script>
let i = document.querySelector("#father")
console.log(i);
</script>
</body>
</html>
```
现在,变量 `i` 将会指向 `id` 为 `father` 的元素,并且不再是空值。