0

因此,我对 javascript 和构建一个网站非常陌生,我试图在页面上添加动画滚动。

要启用动画滚动到我正在使用此代码的链接:

jQuery(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;
        });
    });
})();

要滚动到页面顶部,我正在使用此代码。

//<-- scroll top -->

var $top = jQuery.noConflict();
$top("#scroll-top").hide();

// fade in #scroll-top
$top(window).scroll(function () {
    if ($top(this).scrollTop() > 150) {
        $top('#scroll-top').fadeIn();
    } else {
        $top('#scroll-top').fadeOut();
    }
});

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

他们都可以独立工作,但不能一起工作。谁能帮我找出他们冲突的原因,以及如何解决冲突?

4

1 回答 1

0

So, this is how I fixed my issue:

I removed the conflicting code " // scroll body to 0px on click " and instead use the animated scroll to anchor link to animate both functions, with a placed on top of the page as well.

jQuery(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;
        });
    });
})();

I works fine, but I am missing only one feature, that the javascript recognises internal links that start with anything else than #. Right now it doesn't recognise for example this link http://julebord.bedriftsdesign.no/julebord.html#julemeny. It only works if I use this: #julemeny

于 2013-09-17T05:45:51.033 回答