015-网页应用开发WebApplicationDevelopment(五)

mac2025-01-27  26

 

 

 

 

我们来用js来写一个按钮控制菜单的功能

 

先来一个简单的布局

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> div{ border: 2px solid red; } .div01 { width: 100px; height: 100px; } .div02 { width: 300px; height: 100px; } </style> </head> <body> <div class="div01">Button</div> <div class="div02">Menu</div> </body> </html>

 

现在我们有了一个Button和一个Menu

如果我们用hover选择器的话

可以这样来写

 

hover选择器有三种不同的控制方法

1. 中间什么都不加  控制子元素; 2. ‘+’ 控制同级元素(兄弟元素); 3. ‘~’ 控制就近元素;

 

这边我们的div是同级元素,所以用+号

看下代码

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> div { border: 2px solid red; } .div01 { width: 100px; height: 100px; } .div01:hover + .div02 { display: none; } .div02 { width: 300px; height: 100px; } </style> </head> <body> <div class="div01">Button</div> <div class="div02">Menu</div> </body> </html>

 

 

 

 

 

如果不用hover,而要用点击的话,

就需要用js来实现

我们来写一个js方法

function display(id) { let target = document.getElementById(id); if (target.style.display == 'none') { target.style.display = 'block'; } else { target.style.display = 'none'; } }

 

然后再来看看完整代码

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script> function display(id) { let target = document.getElementById(id); if (target.style.display == 'none') { target.style.display = 'block'; } else { target.style.display = 'none'; } } </script> <style> div { border: 2px solid red; } .div01 { width: 100px; height: 100px; } .div02 { width: 300px; height: 100px; } </style> </head> <body> <div class="div01" onclick="display('menu')">Button</div> <div class="div02" id="menu">Menu</div> </body> </html>

 

 

 

 

 

 

 

 

最新回复(0)