Scroll To Top When DIV Clicked? [closed]

2020-07-06 05:38发布

We all know that scroll to top with named anchors via HTML is possible but is it possible to scroll to the top when another HTML element is clicked that is not surrounded by tags? For instance, a DIV?

EDIT: Apologies all, I did not see this was a duplicate question. I did a search and didn't find anything.

7条回答
再贱就再见
2楼-- · 2020-07-06 06:21

this should work for any block element:

$('#element_id').click(function(){
    $('html, body').animate({scrollTop:0}, 'slow');
    return false;
});

good luck ...

查看更多
Evening l夕情丶
3楼-- · 2020-07-06 06:22

You could listen for a click event on your div and use scrollTo when it is clicked.

window.scrollTo( x-coord, y-coord ):

Scrolls to a particular set of coordinates in the document.

x-coord is the pixel along the horizontal axis of the document that you want displayed in the upper left. y-coord is the pixel along the vertical axis of the document that you want displayed in the upper left.

查看更多
兄弟一词,经得起流年.
4楼-- · 2020-07-06 06:24

You can achieve this by using JavaScript:

$("#my-div").on("click", function() {
    window.scroll(0,0);
});

or with jQuery:

$("#my-div").on("click", function() {
    $(window).scrollTop(0);
});
查看更多
我想做一个坏孩纸
5楼-- · 2020-07-06 06:29

Yes, you might want to do it with Javascript by using

window.scrollTo(0, 0);

and assigning it to the div

<div onclick="window.scrollTo(0, 0);">Element</div>
查看更多
家丑人穷心不美
6楼-- · 2020-07-06 06:38
$('div').on("click",function(){
      $(window).scrollTop(0);
});

You can insert every kind of html tag into the bracket's

查看更多
萌系小妹纸
7楼-- · 2020-07-06 06:40

if you want to go for jquery solution than you can use

$(document).ready(function() {

    $('a[href=#top]').click(function(){
        $('html, body').animate({scrollTop:0}, 'slow');
        return false;
    });

});

html will be

<a name="top"></a>
...
<a href="#top">Back to top</a>

full article : Scroll to the top of a webpage with jQuery

查看更多
登录 后发表回答