javascript - 当设置 document.body.scrollTop = 0时,要如何还原回去?
迷茫
迷茫 2017-04-10 17:08:04
[JavaScript讨论组]
window.onscroll=function(){
      document.body.scrollTop = 0;
            }

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

迷茫
迷茫

业精于勤,荒于嬉;行成于思,毁于随。

全部回复(2)
大家讲道理

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

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

html:

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

</script>

或者
jquery:

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

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

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

    });
});
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号