2017-02-08 39 views
0

我有以下HTML:的jQuery的if..else基於哈希ID提取條件語句

<section> 
    <div class="main" id="second"> </div> 
</section> 
<section> 
    <div class="main" id="third"></div> 
</section> 
<section> 
    <div class="main" id="fourth"></div> 
</section> 

而且下面的jQuery代碼:

<script> 
navlist = []; 
$("#navlist a").each(function(i) { 
    var thisLink = $(this); 
    var thisId = thisLink.attr('href'); 
    var thisTarget = $(thisId); 
    navlist.push({ 
     'anchor': thisLink, 
     'id': thisId, 
     'target': thisTarget 
    }); 
    thisLink.on('click', function(e) { 
     e.preventDefault(); 
     $('html, body').animate({ 
      scrollTop: thisTarget.offset().top 
     }, 800); 
    }); 
}); 
$(window).on('scroll resize', function(e) { 
    $.each(navlist, function(e, elem) { 
     var placement = elem.target[0].getBoundingClientRect(); 
     if(placement.top<window.innerHeight && placement.bottom>0) { 
      history.pushState({}, '', elem.id); 
      console.log('Hash: ' + elem.id); 
      return false; /* Exit $.each loop */ 
     }; 
    }); 
}); 
</script> 

腳本的工作是讓平滑滾動在站點上的不同錨點之間以及在點擊或滾動時更改URL #id。我想在這裏使用帶有從URL中獲取的id的條件語句。

例如:

if(grabbedhashid == "second"){ 
    $(".phone").css('display', 'none'); 
}else{ 
    //display 

} 

但我沒有任何想法,從那裏我可以做到這一點。請幫助我們。

示例URL與ID:http://localhost/sites/fh/index.php#first

+1

你可以分享你的ID爲 –

+0

代碼片段或騙取錢財的URL的一個會更好 –

+0

@ÖzgürErsil更新...但它僅適用於想法和不在本地主機上查看.. –

回答

1

所以基本上你必須在你的滾動功能,使用該腳本可以隱藏手機只在#second,它會爲你工作

$(window).on('scroll resize', function(e) { 
     $.each(navlist, function(e, elem) { 
      var placement = elem.target[0].getBoundingClientRect(); 
      if (placement.top < window.innerHeight && placement.bottom > 0) { 
       history.pushState({}, '', elem.id); 
       console.log('Hash: ' + elem.id); 
       if(elem.id == "#second"){ 
        $(".phone").css('display', 'none'); 
       }else{ 
        $(".phone").css('display', 'block'); 
       } 
      return false; /* Exit $.each loop */ 
      }; 

     }); 
}); 
+0

是這樣的事情..現在在哪裏將此代碼放入我的jQuery代碼中以使其工作? –

+0

你的滾動功能 –

+0

好吧,而不是使用這兩行我不能只使用window.location.hash並將其存儲在ID? –

0

如果你想在滾動/點擊時獲取當前瀏覽器網址,您可以按如下方式獲取它們。如果只想過濾掉#id部分,請使用像(window.location.href.split(「#」);)這樣的字符串過濾器函數。

的JavaScript:

//using href 
var URL = window.location.href; 
//using path 
var URL = window.location.pathname; 

的Jquery:

$(location).attr('href');