媒体查询激活时更改锚点ID

时间:2014-11-13 17:35:52

标签: jquery html media-queries

当我的媒体查询启动时,我试图更改锚标记的ID。这是我目前正在尝试但未通过的代码:

$(window).resize(function() {
    if ($('.container').css('width') == "100%"){
        $("a[href='#Why-Us']").attr("href='#Why-Us-2'");
    }
});

我基本上想用href="#Why-Us"

替换href="Why-Us-2"

感谢。

编辑**我用于平滑滚动的代码

$("a[href^='#']").on('click', function(e) {

// prevent default anchor click behavior
target = this.hash;
e.preventDefault();

// animate
$('html, body').animate({
   scrollTop: $(this.hash).offset().top
 }, 500, function(){

   // when done, add hash to url
   // (default click behaviour)
   window.location.hash = target;
    });
});

$(window).scroll(function() {
    if($(this).scrollTop() > 400) {
        $('.scroll-to-top').fadeIn();
    } else {
        $('.scroll-to-top').fadeOut();
    }
});

$('.scroll-to-top').click(function() {
    $('html, body').animate({scrollTop: 0},800);
    return false;
});

2 个答案:

答案 0 :(得分:0)

不确定测试是否按预期工作,但属性的更改应为

$("a[href='#Why-Us']").attr("href","#Why-Us-2");

通过javascript处理媒体查询更改,请参阅http://wicky.nillia.ms/enquire.js/

enquire.register("screen and (max-width:580px)", {
    match : function() {
        $("a[href='#Why-Us']").attr("href","#Why-Us-2");
    },      

    // OPTIONAL
    // If supplied, triggered when the media query transitions 
    // *from a matched state to an unmatched state*.
    unmatch : function() {
        $("a[href='#Why-Us-2']").attr("href","#Why-Us");
    }

});

使用上述插件进行演示:http://jsfiddle.net/nr2xhzja/

答案 1 :(得分:0)

您使用.attr错误。它应该是::

$(window).resize(function() {
    if ($( window ).width() <= 580) {
        $("a[href='#Why-Us']").attr("href", "#Why-Us-2");
        console.log('window smaller than 580px');
    }
});

这是一个小提琴:http://jsfiddle.net/byzm2bok/