【问题标题】:Responsive Navigation through jquery通过 jquery 进行响应式导航
【发布时间】:2013-05-28 22:43:47
【问题描述】:

我正在尝试让我的导航栏与调整大小一起使用。 当屏幕尺寸减小时,它会转换为选择选项。
它可以工作,但问题是当屏幕尺寸减小时,第一个选项会显示在选择框中,而不是当前选项。

我希望选择框停留在当前选择的选项上。


这是我的代码

jQuery('<select />').appendTo('#navigation');

jQuery('#navigation a').each(function () {
    var el = jQuery(this);
    jQuery('<option />', {
        "value": el.attr("href"),
            "text": el.text()
    }).appendTo('#navigation select');
});

jQuery('#navigation select').change(function () {
    window.location = jQuery(this).find("option:selected").val();
});

我的 jQuery 代码有问题吗?请帮我解决问题

【问题讨论】:

    标签: jquery navigation responsive-design


    【解决方案1】:

    试试这个:(假设链接在活动时具有“选定”类)

    jQuery('<select />').appendTo('#navigation');
    
    jQuery('#navigation a').each(function () {
        var el = jQuery(this);
        var current = jQuery('<option />', {
            "value": el.attr("href"),
                "text": el.text()
        });
    
        url = document.URL.split('/');
        if(url[url.length-1] == current.attr('value'))
            current.prop('selected', true);
        current.appendTo('#navigation select');
    });
    
    jQuery('#navigation select').change(function () {
        window.location = jQuery(this).find("option:selected").val();
    });
    

    对于第二个模板(删除你已经到达那里的&lt;select&gt;):

    jQuery('<select />').appendTo('#navigation');
    
    jQuery('#menu-new-main-menu li a').each(function () {
        var el = jQuery(this);
        var current = jQuery('<option />', {
            "value": el.attr("href"),
                "text": el.text()
        });
    
        if(document.URL == current.attr('value'))
            current.prop('selected', true);
        current.appendTo('#navigation select');
    });
    
    jQuery('#navigation select').change(function () {
        window.location = jQuery(this).find("option:selected").val();
    });
    

    【讨论】:

    • 没有选择的类被添加到选择的选项字段中。我想这是主要问题。如何将选定的类添加到当前选项?
    • 你能在页面上添加一个链接,这样我就可以看到那里发生了什么?您对当前页面链接的样式与其他链接的样式不同吗?
    • 我实际上是在本地主机上工作,但是是的,我正在使用这个模板 - webcodebuilder.com/envato/showcase/blog.html
    • 已更新。我采用了不同的方法,因为模板没有标记当前页面链接。我已经使用 document.URL 检索了 URL,然后将它的最后一部分(例如 blog.html)与当前链接地址相结合。如果找到匹配项 - 添加属性 selected
    • 非常感谢,它可以与html模板一起使用,您是否也可以使其与这种导航代码一起使用-pastebin.com/Rie0W4qg
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多