3

javascript(jQueryではなく)でgototopボタンを作成しようとしています。このボタンに遅延効果を持たせたい:

    var timeOut;
    function scrollToTop() {
      if (document.body.scrollTop!=0 || document.documentElement.scrollTop!=0){
        window.scrollBy(0,-50);
        timeOut=setTimeout('scrollToTop()',10);
       }
      else clearTimeout(timeOut);
    }

HTMLは単純です: <div id="gototop"><a href="#header" onclick="scrollToTop();return false">Back to top</a></div>

スクロールの高さによってボタンの表示・非表示ができません。私が知る限り、次のようにすると、ページが 600 ピクセル下にスクロールされるまでボタンが非表示になりますが、これは機能しません。

    var posit = window.scrollTop();
    if (posit < 900) {
        document.getElementById("gototop").style.display = 'none';
    }

このスタイルが有効にならないのはなぜですか?

私が使用している完全なコードは次のとおりです。

    var posit = window.scrollTop();
    if (posit < 900) {
        document.getElementById("gototop").style.display = 'none';
    }
    var timeOut;
    function scrollToTop() {
      if (document.body.scrollTop!=0 || document.documentElement.scrollTop!=0){
        window.scrollBy(0,-50);
        timeOut=setTimeout('scrollToTop()',10);
       }
       else clearTimeout(timeOut);
      }

ご清聴ありがとうございました。

4

2 に答える 2

2

次のように、onscroll イベント ハンドラーに入れてみてください。

gototop 要素にスタイルを追加します。次に例を示します。

<div id="gototop" onclick="scrollToTop()" style="display:none;"> </div>     


window.onscroll = function(){
    if (window.scrollY < 900) {
        document.getElementById("gototop").style.display = 'none';
    else
        document.getElementById("gototop").style.display = 'block';
}
于 2012-12-11T10:30:25.380 に答える
0

これは、[トップに戻る] ボタンの完全な動作コードです。

<style type="text/css">
#gototop{display:none;position:fixed;right:28px;bottom:10px;z-index:100;}
#gototop a{font-size:14px;font-weight:bold;display:block;padding:5px;text-decoration:none;color:#fff;background:#000;opacity:0.5;border:1px solid #aaa;}
#gototop a:hover{color: #000;text-decoration:underline;background-color:#fff;border: 2px solid #aaa;opacity:0.5;}
</style>

<script type="text/javascript" language="javascript">

// document.documentElement.scrollTop makes it work in Chrome and IE
// 400 is the point from which the button starts showing, you can change it to your needs

gototop = document.getElementById("gototop");

window.onscroll = function(){
    if (window.scrollY < 400 || document.documentElement.scrollTop < 400) {
        gototop.style.display = 'none';
}
    if (window.scrollY > 400 || document.documentElement.scrollTop > 400)
        gototop.style.display = 'block';
}

var timeOut;
function scrollToTop() {
    if (document.body.scrollTop!=0 || document.documentElement.scrollTop!=0){
        window.scrollBy(0,-50);
        timeOut=setTimeout('scrollToTop()',10);
    }
    else clearTimeout(timeOut);
}
</script>

<div id="gototop"><a href="#header" onclick="scrollToTop();return false">Back to Top</a></div>
于 2012-12-12T06:44:24.523 に答える