jQuery的 hide() 和 show() 方法分别用来隐藏和显示 HTML 元素,而 toggle() 方法则可以切换 hide() 和 show() 方法,也就是显示被隐藏的元素,并隐藏已显示的元素。
1
2
3
|
$(
"select"
).hide();
// 隐藏下拉框
$(
"select"
).show();
// 显示下拉框
$(
"select"
).toggle();
// 如果下拉框是显示的则隐藏之,反之亦然
|
示例代码如下
-
创建Html元素
1234567891011<
div
class
=
"box"
>
<
span
>点击按钮可以显示或隐藏下拉框:</
span
>
<
div
class
=
"content"
>
<
select
name
=
"test"
>
<
option
value
=
"0"
>请选择一个项目</
option
>
<
option
value
=
"1"
>我不选</
option
>
<
option
value
=
"2"
>选就选吧</
option
>
</
select
>
</
div
>
<
input
type
=
"button"
value
=
"显示"
>
</
div
>
-
设置css样式
12345div.box{
width
:
300px
;
padding
:
20px
;
margin
:
20px
;
border
:
4px
dashed
#ccc
;}
div.box span{
color
:
#999
;
font-style
:
italic
;}
div.content{
width
:
250px
;
margin
:
10px
0
;
padding
:
20px
;
border
:
2px
solid
#ff6666
;}
select{
width
:
150px
;
height
:
30px
;
border
:
1px
solid
#6699FF
;}
input[type=
'button'
]{
height
:
30px
;
margin
:
10px
;
padding
:
5px
10px
;}
-
编写jquery代码
1234567$(
function
(){
$(
"select"
).hide();
// 默认隐藏下拉框
$(
":button"
).click(
function
() {
$(
"select"
).toggle();
// 已经显示则隐藏,隐藏了则显示
$(
this
).val($(
this
).val()==
"显示"
?
"隐藏"
:
"显示"
);
})
})
-
观察效果
本文源自:https://zhidao.baidu.com/question/184538523.html