繁体   English   中英

单击锚点时更改href

[英]Change href when anchor is clicked

我有一个关于如何动态更改按钮中的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。 当用户手动滚动到某个部分时,显然也需要进行更改。

这是针对单页网站的。 我将如何处理这样的事情?

使用.prop()更改其值

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

演示

我不习惯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%;
        }

我为此编写了一个小jQuery插件,将其推送到GitHub。 https://github.com/ferdinandtorggler/scrollstack

你基本上想做的就是打电话

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

在按钮上调用该链接时,您甚至不需要链接。 因此,请检查出来,让我知道它是否适合您。 ;)

在这里您可以尝试并阅读更多内容: http : //ferdinandtorggler.github.io/scrollstack/

您可以使用fullPage.js插件来实现所需的功能。 也许它比使用cero编码要快:)

暂无
暂无

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

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