我正在尝试创建一个简单的博客,就像练习网站一样,可以隐藏或显示一侧的菜单。我试图在外部javascript文件中使用本机javascript来实现这一点。我的问题是,一旦网站加载,我的事件就会被触发,或者根本不会触发它们。我确定我犯了一些noobie错误。这是我的代码:
Javascript:
var shower = document.getElementById('showmenu');
var hider = document.getElementById('site');
function hideshow() {
shower.onclick = function() {
document.getElementById('site').style.width="84%";
document.getElementById('menu').style.display="block";
document.getElementById('showmenu').style.display="none";
}
hider.onclick = function() {
document.getElementById('menu').style.display="none";
document.getElementById('site').style.width="100%";
document.getElementById('showmenu').style.display="block";
}
}
window.onload = function() {
hideshow();
}
HTML:
<!doctype html>
<meta charset="utf-8">
<html>
<head>
<title> Javascript Menu Test 2.0</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div id="wrapper">
<div id="menu">
<aside>
<ul>
<li><input type="text"></li>
<li>Vel Purus</li>
<li>Dolor Sit</li>
<li>Lorem Ipsum</li>
</ul>
</aside>
</div>
<div id="site">
<div id="bannerImage">
<input type="button" value="M" id="showmenu">
<img src="banner.jpg">
</div>
<div id="article">
<h1> Header</h1>
<!--text goes here-->
</div>
</div>
</div>
</div>
<script type="text/javascript" src="menuhider.js"></script>
</body>
</html>
CSS:
html,body {
height: 100%;
width: 100%;
margin: 0;
padding: 0;
}
ul {
margin: 0;
padding: 0;
}
#wrapper {
height: 100%;
height: 100%;
}
#menu {
display: none;
position: fixed;
height: 100%;
width: 16%;
background-color: #131313;
float: left;
color: white;
font-family: 'arial', sans-serif;
}
#menu li {
margin-top: 8%;
margin-left: 1%;
padding-top: 1%;
padding-bottom: 1%;
}
#menu li:hover {
cursor: pointer;
background-color: #424242;
}
#menu input {
border: none;
outline: none;
}
#site {
height: 100%;
width: 100%;
background-color: white;
float: right;
}
#site img {
position: relative;
z-index: 0;
width: 100%;
height: 10%;
}
#showmenu {
position: absolute;
position: fixed;
z-index: 1;
border: none;
width: 5%;
height: 5%;
margin-left: 1%;
background-color: #131313;
color: white;
outline: none;
}
#showmenu:hover {
cursor: pointer;
background-color: #424242;
}
#text {
width: 85%;
margin-left: 5%;
font-size: 1.2em;
}
答案 0 :(得分:0)
当scrpt包含在底部时,没有理由使用window.onload。删除它,只包括功能。
另一个问题是你有两个嵌套的点击事件。
所以他们俩都会被触发。您需要取消内部单击,以便它不会传播到父级。
(function(){
var shower = document.getElementById('showmenu');
var hider = document.getElementById('site');
hider.onclick = function() {
document.getElementById('menu').style.display="none";
document.getElementById('site').style.width="100%";
document.getElementById('showmenu').style.display="block";
}
shower.onclick = function (e) {
document.getElementById('site').style.width="84%";
document.getElementById('menu').style.display="block";
document.getElementById('showmenu').style.display="none";
if (!e) {
e = window.event;
}
if (e.stopPropagation) {
e.stopPropagation();
} else {
e.cancelBubble = true;
}
return false;
}
})();