我正在試圖製作一個簡單的博客,就像可以隱藏或顯示的一側的菜單一樣。我試圖讓這種情況發生在外部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;
}
隱藏似乎工作正常,但是當你隱藏時,你也隱藏了你正在使用的一個元素來顯示的東西。如果你將它從隱藏的元素中移出,它似乎可以正常工作http://jsfiddle.net/j08691/jkQyd/ – j08691