2016-12-17 23 views
1

我设立的网页上,这样,在一定的宽度,右边滑动菜单将成为从上到下滑动菜单。 要做到这一点,我用JavaScript来改变按钮的onclick属性,但仍网页坚持工作像以前一样,用向左滑动效果的权利。我附上与菜单相关的代码。设置使用javascript新onclick属性不工作

HTML:

<div id="header"> 
    <header id="title"> 
     <h1>The Nest</h1> 
     <p id="para">The hostel where your journey should start</p> 
     <button type="button" class="btn btn-lg" id="menu-btn" onclick="openSide()"> 
      <span class="glyphicon glyphicon-list"></span> 
     </button> 
    </header> 
</div> 

<div id="sidebar"> 
    <a href="javascript:void(0)" id="close-btn" onclick="closeSide()">&times;</a> 
    <a href="#">Accomodations</a> 
    <a href="#">Services</a> 
    <a href="#">Merchandising</a> 
    <a href="#">About us</a> 
</div> 

的JavaScript & jQuery的:

var main = function() { 


$(window).resize(function() { 

    var width = $(window).width(); 

    if (width < 1023) { 

     document.getElementById("para").innerHTML = "Barcellona fine stay"; 

     $("#menu-btn").click(function() { 
     $("#para").fadeOut("fast"); 
     $("#menu-btn").fadeOut("fast"); 
     }); 

     $("#close-btn").click(function() { 
     $("#para").fadeIn("slow"); 
     $("#menu-btn").fadeIn("slow"); 
     }); 
    }  

    else if (width > 1024) { 

     document.getElementById("para").innerHTML = "The hostel where your journey should start"; 

    } 

    else if (width < 380) { 

     document.getElementById("menu-btn").onclick = function() { openTop(); }; 
     document.getElementById("close-btn").onclick = function() { closeTop(); }; 

     $("#menu-btn").click(function() { 
     $("#header").fadeOut("fast"); 
     }); 

     $("#close-btn").click(function() { 
     $("#header").fadeIn("slow"); 
     }); 

    }  

    return true; 

}); 

} 

$(document).ready(main); 

我刚刚加入整个if/else语句,因为它似乎整个最后的 “否则,如果” 它不工作

+0

为什么不检查宽度事件处理程序中,而不是试图取代它们 – adeneo

+1

为什么你混合使用'getElementById'和东西... jQuery的语法? – trincot

+3

我会建议删除内联事件在你的HTML处理,并在您的JS文件的事件处理程序做的一切,如果你真的想保持的onclick在HTML中,执行该函数的一切,但我不建议对那。内联事件处理有时会导致怪异的错误。 [点击这里了解更多信息。(http://stackoverflow.com/a/21975639/6006586) –

回答

1

试着改变它:

$("#menu-btn").click(function() { 
    $("#header").fadeOut("fast"); 
}); 

这个

$("body").on('click', '#menu-btn', function() { 
    $("#header").fadeOut("fast"); 
}); 

它应该有帮助,因为jQuery方法click没有动态元素,添加后DOM准备和分析工作。

+0

问题中没有任何内容表示他正在动态添加元素。如果他这样做,'document.getElementById(“menu-btn”)。onclick = function(){openTop(); };'会得到一个错误,因为它会尝试访问'nul​​l'的'onclick'属性。 – Barmar