要点:
1.本人原来用的是IDEA编译器,因为什么环境都配置好了,代码提示功能也好,界面也优美,可惜什么都好导致太庞大。本人在自习室敲代码,笔记本电池管不了一上午,后用sublime,真轻便哈哈。但是里面的插件的代码其实,应该是只收录了js的关键字,然后给的提示,并不会筛选。这里,因为前段时间写网页布局,用了很多浮动,有个overflo:hidden经常用,这里写了display:hidden,并且还是提示出来的。找了半天原因,所以,不要相信此编译器插件的提示,看API。
2. 通过第一种方式,改变display属性,注意一定不要直接使用 my$(id).display来修改样式,要在前面加上.style如my$(id).style.display
通过第二种方式,主要记住class属性不能通过my$(id).class这样会跟关键字冲突,改成my$(id).className
html和js代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style type="text/css">
#div{
width: 250px;
height: 250px;
background-color: greenyellow;
display: none;
//默认不显示
}
.show{
width: 250px;
height: 250px;
background-color: greenyellow;
}
</style>
</head>
<body>
<input type="button" value="显示" id="btn">
<div id="div"></div>
<br/>
<input type="button" value="显示" id="btn2">
<div id="div2"></div>
<script type="text/javascript">
function my$(id){
return document.getElementById(id);
}
//封装通过元素id名,获取元素的方法
my$("btn").onclick=function(){
if(this.value == "显示"){
my$("div").style.display="block";
this.value="隐藏";
// 默认不显示,改变其状态
}else{
my$("div").style.display="none";
this.value="显示";
// 通过点击后成显示状态,改为不显示状态
}
}
</script>
<script type="text/javascript">
function my$(id){
return document.getElementById(id);
}
//封装通过元素id名,获取元素的方法
my$("btn2").onclick = function(){
if(my$("div2").className != "show"){
my$("div2").className = "show";
this.value = "显示";
// 一开始默认的是没有class类名,所以没有效果视觉效果是隐藏,其实是没有样式
// 通过响应点击事件,将元素
}else{
my$("div2").className = "hidden";
this.value = "隐藏";
}
}
</script>
</body>
</html>
效果: