Simple “scroll to/down” effect using minimal markup and hash tags

喜夏-厌秋 提交于 2019-12-22 05:13:42

问题


I am making a one page site that has a classic navigation at the top. Right now I have links set up as hash tags in order to navigate within the page:

<nav>
<a href="#about">About</a>
</nav>
...
<section id="about">...</section>

Obviously, this works but the jump to the about section is instant and not gradual. I am looking for an extremely simple implementation in order to make a gradual transition. I don't want anything fancy. No axis, offset, or any other options. I just want the scroll transition to be gradual. The only setting I want is the time it takes to finish the scroll. Also, I want to make almost no changes to my markup. I have seen several javascript plugins that require you to use anchor tags to set the locations in the html document— i don't want that. This site looks promising, but I don't know how to set it up. There is no demo so I can't see how to set it up. I am not that literate in Javascript. Also, the ScrollTo plugin for jQuery is way too complicated. I am willing to use a plugin that has a lot of options, but I just don't want the options to prevent me from figuring out how to set it up.

Any help would be much appreciated!


回答1:


This is the best way I have found to do it - it just uses the normal anchors but extends their functionality

$('a').click(function() {
    var elementClicked = $(this).attr("href");
    var destination = $(elementClicked).offset().top;
    $("html:not(:animated),body:not(:animated)").animate({ scrollTop: destination-15}, 500);
});

Here is a live example




回答2:


I used straight jquery to do this.

I had a link like so ->

<a href="1" class="scrolling">Go to 1</a>

then using jquery it would scroll down to a div with another anchor with id "1"

$("a.scrolling").click(function(e) {
    e.preventDefault();
    goToByScroll($(this).attr("href"));
});

function goToByScroll(id) {
    $('html,body').animate({scrollTop: $("#"+id).offset().top},'slow');                               
}                       



回答3:


There's ScrollTo in Javascript. It's a window event. check it out here: https://developer.mozilla.org/en/DOM/window.scrollTo




回答4:


I found this code over the internet while searching for a quick way to create this scroll to effect.

html code:

<a href="#services">Jump to services</a>
<div id="services"></div>

jQuery code:

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

    var target = this.hash,
    $target = $(target);

    $('html, body').stop().animate({
        'scrollTop': $target.offset().top
    }, 900, 'swing', function () {
        window.location.hash = target;
    });
});

});

This is the Code source.



来源:https://stackoverflow.com/questions/10403513/simple-scroll-to-down-effect-using-minimal-markup-and-hash-tags

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!