2016-02-11 3 views
-1

сэр. Я хочу установить блок стиля div, если div-стиль отображения отсутствует, и установить none, если div-стиль является блоком. Я пишу этот код, но его не работает, что делать?Показать div, если это стиль отображения, нет и скрывать, если стиль отображения является блоком

<style> 
    * { 
     margin: 0px; 
     padding: 0px; 
    } 

    #menu { 
     width: 100%; 
     height: 40px; 
     z-index: 100; 
     cursor: pointer; 
     background: url(images/menu.jpg) center no-repeat; 
     margin: auto; 
    } 

    #line { 
     margin-top: 19px; 
     position: absolute; 
     left: 5%; 
     z-index: -1; 
     width: 90%; 
    } 

    #menu_element { 
     height: 240px; 
     background: #06C; 
     display: none; 
     width: 100%; 
    } 

    @keyframes menu_animate { 
     from { 
      height: 0px; 
     } 
     to { 
      height: 240px; 
     } 
    } 

    @keyframes menu_animate_reverse { 
     from { 
      height: 240px; 
     } 
     to { 
      height: 0px; 
     } 
    } 
</style> 

<script> 
    function menuShow() { 
     if (document.getElementById("menu_element").style.display == "none") { 
      document.getElementById("menu_element").style.display = "block"; 
      document.getElementById("menu_element").style.animationName = "menu_animate"; 
      document.getElementById("menu_element").style.animationDuration = "1s"; 
     } 
     if (document.getElementById("menu_element").style.display == "block") { 
      document.getElementById("menu_element").style.display = "none"; 
      document.getElementById("menu_element").style.animationName = "menu_animate_reverse"; 
      document.getElementById("menu_element").style.animationDuration = "1s"; 
     } 
    } 
</script>` 

<div id="menu" onClick="menuShow();"></div> 
<div id="menu_element"></div> 

что случилось с моим кодом? поэтому мне нужно после нажатия меню id, если id 'menu_element' нагляден, ему нужно скрыть, а затем скрыться и показать его.

+0

тумблер класса. – epascarello

+1

может убрать код ur в jsfiddle или codepen. с вопросом ?. – Pbk1303

+3

Используйте 'else if' для второго блока' if'. Поскольку в настоящее время ваш первый 'if' в конечном итоге устанавливает стиль элемента' block', а второй 'if' будет всегда иметь значение true, поскольку он был просто установлен как' block' –

ответ

3

Вы можете удалить onclick вообще, если у вас есть несколько элементов #menu. Использование JQuery ...

$(document).ready(function() { 
    $(#menu).click(menuShow()); 
} 

function menuShow() { 
    if ($(this).css('display')=='block') { 
     $(this).css('display', 'none'); 
    } else if ($(this).css('display')==('none') { 
     $(this).css('display', 'block'); 
    } 
} 

Если вы имели больше случаев отображения вы хотели обратиться, коммутатор заявление может быть лучшим выбором.

+0

'$ (# menu)' , думаю, вы имели в виду '$ ('# menu')'. _ «если у вас есть несколько элементов #menu», даже если они и должны были быть уникальными, селектора id будут возвращать только один элемент. Также вы выполняете 'menuShow' немедленно, а не передаете его. –

0
<html> 
<head> 
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script> 


<script>function menuShow(){ 
debugger 
    var curr=document.getElementById("menu_element"); 
    if(curr.style.display == "none"){ 
    document.getElementById("menu_element").style.display ="block"; 
    document.getElementById("menu_element").style.animationName ="menu_animate"; 
    document.getElementById("menu_element").style.animationDuration = "1s"; 
    } 
    else if(curr.style.display == "block"){ 
    document.getElementById("menu_element").style.display ="none"; 
    document.getElementById("menu_element").style.animationName ="menu_animate_reverse"; 
    document.getElementById("menu_element").style.animationDuration = "1s"; 
    } 
    } 
     </script> 

</head> 
<body> 
<div id="menu" onClick="menuShow();"> 
Click me to hide 
</div> 
<div id="menu_element" style="background-color:red;display:block;" > 
I Love this code. 
</div> 
</body> 
</html> 
0

document.getElementById("menu_element").style.display может быть none или просто пустая строка "": Проверьте jsfiddle здесь:

jsfiddle

-1
function menuShow(){ 
    if(document.getElementById("menu_element").css('display') == "none"){ 
     document.getElementById("menu_element").css("background-color", "block"); 
     document.getElementById("menu_element").css("animationName", "menu_animate"); 
     document.getElementById("menu_element").css("animationDuration", "1s"); 
    } 
    if(document.getElementById("menu_element").css('display') == "block"){ 
     document.getElementById("menu_element").css("background-color", "none"); 
     document.getElementById("menu_element").css("animationName", "menu_animate_reverse"); 
     document.getElementById("menu_element").css("animationDuration", "1s"); 
    } 
    } 
+0

Uncaught TypeError: Невозможно прочитать свойство 'css' нулевого –

+0

var curr = document.getElementById ("# menu_element"); всегда null.please проверить код –

+0

вы можете просто добавить &&! = NULL, – WelshBoyZz

0

попробовать нижеуказанным образец.

<!doctype html> 
 
<html> 
 
    <head> 
 
     <meta charset="utf-8"> 
 
     <meta http-equiv="X-UA-Compatible" content="IE=edge"> 
 
     <meta name="description" content=""> 
 
     <meta name="viewport" content="width=device-width, initial-scale=1"> 
 
     <title>Menu Show or Hide by java script</title> 
 
     
 
     <script type="text/javascript"> 
 
      function showOrHide(){ 
 
       var melement = document.getElementById('menu_element'); 
 
       
 
       if(melement.style.display == 'none'){ 
 
        melement.style.display = 'block'; 
 
       } 
 
       else{ 
 
        melement.style.display = 'none'; 
 
       } 
 
      } 
 
     </script> 
 
    </head> 
 
    <body> 
 
     <div id="menu" onclick="showOrHide();" style="width:100px; height:100px; border:1px solid red;"> 
 
     </div> 
 
     <div id="menu_element" style="width:100px; height:100px; border:1px solid red;"> 
 
     </div> 
 
     
 
    </body> 
 
</html>

Смежные вопросы