我一直在搞這個代碼一段時間,我卡住了。我手工編寫了很多代碼,但現在只是用HTML5,CSS3和Javascript來增加新的功能。Javascript CSS3:移動div容器
我試圖做一個簡單的菜單,上下滑動。我有一個包含一切的div。 div的溢出設置爲隱藏狀態,所以當菜單離開查看框時,它不能被看到。然後它可以在視圖框中進出動畫。
我一直在嘗試使用Javascript函數來實現它,但它聽起來像使用CSS3轉換更容易?有什麼建議?
我的Javascript代碼如下。我無法弄清楚如何用CSS3轉換來完成它。任何意見將不勝感激。
的Html
<header>
<nav>
<div id="mobileMenu" class="mobileMenu">
<div id="mobileMenuWrapper" class="mobileMenuWrapper">
<div style="height: 100px; width: 100%;">
<div style="height: 100px; width: 100%; background-color: black; color: white;">
Menu option<br>Menu option<br>Menu option
</div>
</div>
<div style="position: relative; height: 50px; width: 100%; left: 50px;">
<div style="height: 50px; width: 125px; background-color: black; color: white; text-align: center;"><a href="javascript:moveMenuDown();">Menu</a></div>
</div>
</div>
</div>
</nav>
</header>
的Javascript
var startPosition = -100;
var endPosition = 0;
var speed = 2;
function moveMenuDown(){
// Get the element
menu = document.getElementById("mobileMenuWrapper");
// Grab the element's current CSS top position
currentPosition = Number(menu.style.top.substr(0,(menu.style.top.length-2)));
// Compare the position and move it
if(currentPosition <= endPosition){
// I'm stuck about the line below...how can I attach a CSS3 transition here? Or should I?
menu.style.MozTransition = ???;
// Here's my original code where I move the element manually
menu.style.top = (currentPosition + speed) + 'px';
moveMenuDown();
}else{
}
}
更新整個HTML/CSS/JavaScript的
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Menu test</title>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<style>
.mobileMenu {
position: absolute;
height: 150px;
width: 250px;
top: 0px;
left: 50px;
overflow: hidden;
}
#mobileMenuWrapper {
margin-top:-100px;
transition: margin-top 0.5s ease;
}
#mobileMenuWrapper.show {
margin-top:0px;
}
</style>
<script type="text/javascript">
function moveMenuDown(){
menu = document.getElementById("mobileMenuWrapper hide");
if(menu.className=="mobileMenuWrapper hide"){
menu.className = menu.className.replace('hide','show');
}else{
menu.className = "mobileMenuWrapper hide";
}
}
</script>
</head>
<body>
<header>
<nav>
<div id="mobileMenu" class="mobileMenu">
<div id="mobileMenuWrapper" class="mobileMenuWrapper hide">
<div style="height: 100px; width: 100%;">
<div style="height: 100px; width: 100%; background-color: black; color: white;">
Menu option<br>Menu option<br>Menu option
</div>
</div>
<div style="position: relative; height: 50px; width: 100%; left: 50px;">
<div style="height: 50px; width: 125px; background-color: black; color: white; text-align: center;"><a href="javascript:moveMenuDown();">Menu</a></div>
</div>
</div>
</div>
</nav>
</header>
</body>
</html>
你應該只使用CSS完全。爲什麼你會在這種情況下使用JS腳本來添加CSS轉換?我的建議:擺脫這個JS。 – rnevius 2014-11-02 16:09:55
我不確定。我不熟悉CSS3轉換以及它們如何工作。我會研究並找出它們。謝謝。 – flasshy 2014-11-02 16:10:44
@flasshy,你可以發佈當前的HTML/CSS嗎?你如何激活上/下滑動? (點擊或懸停)? – sinisake 2014-11-02 16:20:07