简体   繁体   English

导航菜单未在浏览器中呈现

[英]Navigation Menu not rendering in browser

I made a navigation menu for my website to be used when people access the site on their phone. 我制作了一个导航菜单,供我的网站在人们通过手机访问该网站时使用。 For some reason, I can see this working only on the fiddle I made, but not when I test it in my browser. 出于某种原因,我只能在我制作的小提琴上看到它的工作原理,而在浏览器中测试时却看不到。

I've tested it with Chrome, and the latest version of IE, but I don't see the responsive navigation menu I made when I shrink my browser's size. 我已经在Chrome和最新版的IE上进行了测试,但是在缩小浏览器尺寸时看不到响应式导航菜单。

This is exactly what my javascript file looks like: 这正是我的javascript文件的样子:

$("#nav").addClass("js").before('<div id="menu">&#9776; MENU </div>');
$("#menu").click(function(){
    $("#nav").toggle();

});

$(window).resize(function(){
    if(window.innerWidth > 768){
        $("#nav").removeAttr("style");

    }
});

Here is my fiddle: 这是我的小提琴:

http://jsfiddle.net/Nuxj6/ http://jsfiddle.net/Nuxj6/

And my CSS file and HTML file have the same code as in the fiddle. 我的CSS文件和HTML文件与小提琴中的代码相同。 The only thing that is different is that I have another CSS file for the rest of my site. 唯一不同的是,我的网站其余部分都有另一个CSS文件。 This CSS file is only for the navigation menu. 此CSS文件仅用于导航菜单。 I tried importing the CSS file with the navigation menu into my main CSS file, but it didn't work either. 我尝试将带有导航菜单的CSS文件导入到我的主CSS文件中,但是它也不起作用。

I would appreciate any advice on fixing this issue. 对于解决此问题的任何建议,我将不胜感激。 As I said, it works in the fiddle, but not in my browser. 就像我说的,它只能在小提琴中起作用,而不能在我的浏览器中起作用。 Thanks in advance. 提前致谢。

You should run your code when DOM is ready or #nav is parsed by browser, or jQuery cannot find #nav . 当DOM准备就绪或浏览器已解析#nav或jQuery无法找到#nav时,应运行代码。 So you may have 2 alternative ways: 因此,您可能有2种替代方法:

  • Run your code when Dom is ready just like: Dom准备就绪时运行代码,如下所示:

     $(function() { $("#nav").addClass("js").before('<div id="menu">&#9776; MENU </div>'); $("#menu").click(function(){ $("#nav").toggle(); }); $(window).resize(function(){ if(window.innerWidth > 768){ $("#nav").removeAttr("style"); } }); }); 
  • Put your js code at the bottom of your HTML. 将您的js代码放在HTML的底部。

Why jsfiddle works? 为什么jsfiddle有效?

That's because jsfiddle will wrap js code with $(window).load like below if you use jQuery: 这是因为如果您使用jQuery,jsfiddle将使用$(window).load .load包裹js代码,如下所示:

$(window).load(function(){
    $("#nav").addClass("js").before('<div id="menu">&#9776; MENU </div>');
    ...
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM