【问题标题】:How to create a center div scrolling with the page?如何创建与页面一起滚动的中心 div?
【发布时间】:2010-11-18 05:04:53
【问题描述】:

我有一个网站,我想在该网站上方放置一个 DIV,其中包含输入电子邮件的字段和“订阅”按钮。它应该像我们都喜欢的广告一样工作。所以这个 div 应该始终位于屏幕的中心,并且它应该在网站“上方”并在用户浏览页面时滚动。当用户点击 X 时它应该关闭。

如何做到这一点?

【问题讨论】:

    标签: javascript html css


    【解决方案1】:

    查看 CSS position:fixedz-index 属性。要将项目水平和垂直居中,给它固定尺寸,将其定位在 50%,50%,然后使用负边距。例如:

    #annoying-floater {
      z-index:10;
      position:fixed;
      top:50%; left:50%;
      width:640px; height:480px;
      margin-left:-320px; margin-top:-240px
    }
    

    要“关闭”它,请通过 JS 将 display 设置为 none。例如:

    window.onload=function(){
      document.getElementById('annoying-floater-closer').onclick = function(){
        document.getElementById('annoying-floater').style.display='none';
      }
    }
    

    【讨论】:

    • 如何使它在 IE8 中工作?矩形在浏览器窗口的最左侧。
    • @tomaszs 它在 IE8 中对我来说可以正常工作,无论是在兼容性视图中还是在兼容性视图之外。这是a simple test case 的实际应用。
    【解决方案2】:

    你的意思是当页面滚动时 div 将保持居中?在这种情况下,使用 position: fixed 来放置你的 div;除了 this

    【讨论】:

    • 哦,是的,还有 z-index。
    猜你喜欢
    • 2012-09-23
    • 1970-01-01
    • 2012-11-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-30
    • 1970-01-01
    相关资源
    最近更新 更多