简体   繁体   English

如何在<div>底部添加“返回顶部”链接浏览器窗口比页面短,使用jquery?

[英]How to add “Back to top” link at bottom at <div> is browser window is shorter than page, using jquery?

How to add "Back to top" link at bottom at is browser window is shorter than page, using jquery? 如何在浏览器窗口底部添加“返回顶部”链接比页面短,使用jquery?

<div id="mainContent">

<p>Some content</p>

</div>

If some content is bigger than browser window ( I mean if vertical bar comes on the page) then i want to add Back to top just before closing the div. 如果某些内容大于浏览器窗口(我的意思是如果页面上有垂直条),那么我想在关闭div之前添加Back to top。

<div id="mainContent">

<p>Some content</p>

<p>Some content</p>

<p>Some content</p>

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

</div>

If browser has vertical scroll bar and user go to bottom at page then I want to show "Back to top" link. 如果浏览器有垂直滚动条,用户到页面底部,那么我想显示“返回顶部”链接。

Write some code to run when the page is finished loading: 编写一些代码以在页面加载完成时运行:

$(function(){
    if( $(window).height() < $("#mainContent").height() ) {
        $("#mainContent").append('<a href="#mainContent">Back to top</a>');
    }
});

This is as simple as can be; 这很简单; we use the jQuery height method to see whether we need a return link, and add one if we do in our document.ready callback . 我们使用jQuery 高度方法来查看是否需要返回链接,如果我们在document.ready回调中添加一个,则添加一个。 The return link uses the id attribute of the very same div which contains it to take the user back to the top of the page. 返回链接使用包含它的同一divid属性将用户带回页面顶部。 (If this main content div is not at the very top of the page, you'll need to make a separate div with its own id which is; this div may be empty so long as it has an id attribute.) (如果这个主内容div不在页面的最顶层,你需要创建一个单独的div,它有自己的id;这个div可能是空的,只要它有一个id属性。)

Normal HTML: 普通HTML:

<div id="mainContent">
<a name="backToTop" />
<p>Some content</p>
<p>Some content</p>
<p>Some content</p>
<a href="#backToTop"> Back to top </a>
</div>

jQuery: using ScrollTo ( http://plugins.jquery.com/project/ScrollTo ) jQuery:使用ScrollTo( http://plugins.jquery.com/project/ScrollTo

<div id="mainContent">
<p>Some content</p>
<p>Some content</p>
<p>Some content</p>
<a href="$(\"#backToTop\").localScroll()">Back To Top</a>
</div>

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

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