2013-10-06 38 views
0

我有一個關於如何在按鈕中動態更改href=""的問題。單擊錨時更改href

下的jsfiddle示出固定在視口的底部處的按鈕開始於着陸頁:

http://jsfiddle.net/Hm6mA/3/

按鈕的HTML是像這樣:

<div class="button"> 
    <a href="#first" class="" style="width: 80px; height: 80px; opacity: 1;"> 
     <img src="img/down.png" alt="down"> 
    </a> 
</div> 

當點擊我希望它滾動到下一節,並將href =「」更改爲頁面的以下部分。所以,當它第一次點擊時,href將變成#second。當用戶手動滾動過去某個部分時,顯然也需要更改。

這是一個單頁網站。我將如何去做這件事?

回答

2

使用.prop()來改變其值

$(".button").on('click', function(){ 
    $('.button').find('a').prop('href', '#services'); 
}); 

Demo

+0

我剛添加到[鏈接](http://jsfiddle.net/Hm6mA/10/)編碼更快徒勞無功。 @Satpal –

+0

我剛剛更新鏈接,因爲他們之前被打破。我已經嘗試過你的新解決方案,但仍然有複雜性。謝謝[鏈接](http://jsfiddle.net/Hm6mA/15/)@Satpal –

+0

@DizzyChamp,什麼併發症親愛的? – Satpal

1

我不習慣的jQuery。這裏是一個純JavaScript解決方案。它肯定會改變散列值。

<body> 

    <div id="sections"> 

     <section id="s100">asdfasd</section> 
     <section id="s101"></section> 
     <section id="s102"></section> 
     <section id="s103"></section> 
     <section id="s104">asdfasdasdfsdf</section> 
     <section id="s105"></section> 

    </div> 

    <div class="nav-bar"> 

     <a id="next-button" class="button" href="#s100">Next</a> 

    </div> 

    <script type="text/javascript"> 

     var sections = document.getElementById("sections"); 

     var nextButton = document.getElementById('next-button'); 

     sections.onscroll = function (evt) { 

     } 


     var counter = 100; 
     var limit = 105; 

     // closure 
     nextButton.onmouseup = function (evt) { 

      var incCounter = function() { 
       // add your custom conditions here 

       if(counter <= limit) 
        return counter++; 
       return 0; 
      }; 

      var c = incCounter(); 
      if(c != 0) 
       this.setAttribute('href', "#s" + c); 
     } 

    </script> 

</body> 

CSS

html, body { 
      height: 100%; 
      width: 100%; 
      overflow: hidden; 
     } 

     #sections { 
      height: 50%; 
      width: 100%; 
      overflow: scroll; 
     } 

     .nav-bar { 
      margin: 30px 20px; 
     } 

     .button { 
      text-decoration: none; 
      border: 1px solid #999; 
      padding: 10px; 
      font-size: 120%; 
     } 
1

我寫了一個小的jQuery插件的是,只需將它推到GitHub上。 https://github.com/ferdinandtorggler/scrollstack

什麼你基本上想要做的就是調用

$('.button').scrollstack({stack: ['#first', '#second', ... ]});

你甚至需要鏈接時,你把它的按鈕。所以檢查一下,讓我知道它是否適合你。 ;)

在這裏,你可以嘗試一下,瞭解更多:http://ferdinandtorggler.github.io/scrollstack/

+0

我嘗試了你的網站,並且按鈕只在你第一次點擊時才起作用... –

+0

感謝您試用它,請告訴我你使用的瀏覽器是什麼?對我來說,它適用於Chrome和Firefox,但我一定會盡力解決這個問題:) –

+1

好的,現在應該修復:) –