如果浏览器高度比页面短,如何使用jquery显示“返回顶部”按钮?

时间:2021-07-06 06:07:32

How to add/show "back to top" button at bottom in a div using jquery only if height browser height is shorter than page, other wise it should be hidden?

如果高度浏览器高度比页面短,如何使用jquery在div的底部添加/显示“返回顶部”按钮,否则应该隐藏它?

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

to this

<div id="mainwrapper">

<p> Paragraph 1 </p>

<p> Paragraph 1 </p>

<p> Paragraph 1 </p>

<p> Paragraph 1 </p>

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

</div>

i need almost same like my this question but condition is different How to detect linked PDF on a page and show message to download Adobe reader using jquery?

我需要几乎像我这个问题一样但条件不同如何在页面上检测链接的PDF并显示使用jquery下载Adobe阅读器的消息?

I need lightweight simple solution

我需要轻量级的简单解决方

2 个解决方案

#1


2  

Something like:

var wrapper = $('#mainwrapper');
if (wrapper.outerHeight(true) > $(window).height()) {
   wrapper.append('<p><a href="#' + wrapper.attr('id') + '">Back to top</a></p>');
}

#2


0  

Do something like this:

做这样的事情:

$(document).ready(function(){
    showHideControl();
    $(window).resize(function(){
        showHideControl();
    });        
});

function showHideControl() {
    var h = $(window).height();
    var ch = $("#content").height();
    if (ch < h) {
        $("#backControl").hide();
    }
    else {
        $("#backControl").show();
    }
}

The html needs to be updated a little too:

html需要稍微更新一下:

<div id="mainwrapper">
<div id="content">
<p> Paragraph 1 </p>

<p> Paragraph 1 </p>

<p> Paragraph 1 </p>

<p> Paragraph 1 </p>
</div>
<p id="backControl"><a href="#mainwrapper">Back to top</a></p>
</div>

#1


2  

Something like:

var wrapper = $('#mainwrapper');
if (wrapper.outerHeight(true) > $(window).height()) {
   wrapper.append('<p><a href="#' + wrapper.attr('id') + '">Back to top</a></p>');
}

#2


0  

Do something like this:

做这样的事情:

$(document).ready(function(){
    showHideControl();
    $(window).resize(function(){
        showHideControl();
    });        
});

function showHideControl() {
    var h = $(window).height();
    var ch = $("#content").height();
    if (ch < h) {
        $("#backControl").hide();
    }
    else {
        $("#backControl").show();
    }
}

The html needs to be updated a little too:

html需要稍微更新一下:

<div id="mainwrapper">
<div id="content">
<p> Paragraph 1 </p>

<p> Paragraph 1 </p>

<p> Paragraph 1 </p>

<p> Paragraph 1 </p>
</div>
<p id="backControl"><a href="#mainwrapper">Back to top</a></p>
</div>