首页 > 当设置 document.body.scrollTop = 0时,要如何还原回去?

当设置 document.body.scrollTop = 0时,要如何还原回去?

window.onscroll=function(){
      document.body.scrollTop = 0;
            }

例如我有一个DIV,它显示的时候我想让窗口的无法滚动固定在当前位置中,所以我写上document.body.scrollTop = 0;
但是问题来了,我让DIV消失的时候怎么让窗体又可以滚动呢?


如果div元素id为div,div内有一个button键,则代码

        var div=document.getElementById('div');
        document.getElementsByTagName('button')[0].onclick=function(){
            document.body.removeChild(div);
            div=null;
        }
            window.onscroll=function(){
                if(div){
                    document.body.scrollTop=0;
                    
                }
            }

html:

<div id="myDivContainer"></div>
<button id="showDivandFix"> show div</button>
<button id="hideDivandremoveFix"> hide div</button>
<script>
    function preventScroll(e){
        //document.body.scrollTop=0;
        e.preventDefault();
    }
    document.getElementById("showDivandFix").addEventListener("click",function(){
        if(!document.getElementById("myDiv")){
            var myDiv = document.createElement("div");
            myDiv.id="myDiv";
            myDiv.style.width="100px";
            myDiv.style.height="100px";
            myDiv.style.backgroundColor='#00ee00';
            document.getElementById("myDivContainer").appendChild(myDiv);
        }
        document.getElementById("myDiv").style.display="block";
        document.body.addEventListener("mousewheel",preventScroll,false);
    },false);
    document.getElementById("hideDivandremoveFix").addEventListener("click",function(){
        document.getElementById("myDiv").style.display="none";
        document.body.removeEventListener("mousewheel",preventScroll,false);
    },false);

</script>

或者
jquery:

$(function(){
    function preventScroll(e){
        //document.body.scrollTop=0;
        e.preventDefault();
    }

    $('button#showDivandFix').on("click",function(){
        if($('#myDiv').length==0){
            $('#myDivContainer').append("<div id='myDiv' style='width:100px;height:100px;background-color: #00ee00'></div>");
        }
        $('#myDiv').show();
        $('body').on("mousewheel",preventScroll);

    });
    $('button#hideDivandremoveFix').on("click",function(){
        $('#myDiv').hide();
        $('body').off("mousewheel",preventScroll);

    });
});
【热门文章】
【热门文章】