Jquery - scroll to div

2019-08-16 01:48发布

I cant make my Jquery work. I put in some code that should make a good looking scroll down to a div further down on the page. I added the HTML around the a tag and the jquery.

HTML

<div id="facebookbanner">   
    <div id="facebookbannertext">
        <div id="knapper">
            <div class="btn_apps"><a href="#fbeksempler"></a></div>
            <div class="btn_bestil"><a href="#"></a></div>
        </div>
     </div>
     <div id="facebookbannerbillede">   
     </div>
 </div>

Jquery

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>

$('#fbeksempler a').on('click', function(evt){
    evt.preventDefault();
    var target = $(this).attr('href');
    $('html, body').stop().animate({scrollTop: $(target).offset().top}, 2000);
});

</script> 

标签: jquery scroll
3条回答
We Are One
2楼-- · 2019-08-16 02:45

I believe the problem is that protocol relative URLs like //ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js don't work when testing locally.
Maybe try http://code.jquery.com/jquery-1.9.1.min.js and see if that works for you.

查看更多
再贱就再见
3楼-- · 2019-08-16 02:50

It appears that the main issue is that you are setting your target variable to a string when you use the .attr() method. You are then trying to scroll to the top of that target, which is not a jQuery object representing a DOM element.

I am assuming what you intend to do is find the jQuery object somewhere on the page that has the ID equal to the href of the link.

$('#facebookbanner a').on('click', function (evt) {
    evt.preventDefault();
    var contentId = $(this).attr('href');
    var content = $(document).find(contentId);
    $('html, body').stop().animate({
        scrollTop: $(content).offset().top
    }, 2000);
});

jsfiddle

查看更多
等我变得足够好
4楼-- · 2019-08-16 02:53

Try wrapping your functionality inside the DOMReady event:

$(function() {
    $('#fbeksempler a').on('click', function(evt){
        evt.preventDefault();
        var target = $(this).attr('href');
        $('html, body').stop().animate({scrollTop: $(target).offset().top}, 2000);
    });
});
查看更多
登录 后发表回答