search

Home  >  Q&A  >  body text

javascript - 如何让页内元素不随着页面滚动?

一个手机上的页面,上面有一块区域,高度固定,有上下滚动条。
如何实现用户在滑动页面的时候,当在这块区域上的时候 只是这块区域的内容滚动,而不是整个页面跟着滚动?

PHPzPHPz2902 days ago641

reply all(5)I'll reply

  • PHP中文网

    PHP中文网2017-04-10 15:12:43

    给元素加上 position:fixed 的style

    reply
    0
  • ringa_lee

    ringa_lee2017-04-10 15:12:43

    这个写起来会有点复杂:思路是当手机上触发touchstart事件的时候,判断触发事件的位置和那块区域的位置,如果在区域内的话,就阻止事件冒泡和事件默认行为,然后记录下位置,当继续触发touchmove事件的时候,也是阻止事件冒泡和事件默认行为,并开始计算位置,然后用这个和之前记录的位置进行比较计算,以计算值来滚动那块区域的内容(需要自己写js代码来滚动它),这也就是常见的模拟滚动了。会有点复杂,祝好。

    reply
    0
  • 怪我咯

    怪我咯2017-04-10 15:12:43

    用touchstart和touchmove控制上部分scrolltop,加e.preventDefault()禁止浏览器默认的滚动(可以判断是否滚到底部,如果是的话则不禁止,这样上面划完了就自然转成滚动全页)。这样就做到上部分触控只滚动它内部,其他区域滚动则是整页滚动。

    reply
    0
  • 高洛峰

    高洛峰2017-04-10 15:12:43

     如果有兴趣可以研究一下ionic.css
    http://ionicframework.com

    body {
        -webkit-font-smoothing: antialiased;
        font-smoothing: antialiased;
        text-size-adjust: none;
        top: 0;
        right: 0;
        bottom: 0;
        left: 0;
        overflow: hidden;
        margin: 0;
        padding: 0;
        color: #000;
        word-wrap: break-word;
        font-size: 14px;
        line-height: 20px;
        text-rendering: optimizeLegibility;
        -webkit-backface-visibility: hidden;
        -ms-content-zooming: none;
    }
    .main {
        position: absolute;
        top: 0;
        right: 0;
        bottom: 0;
        left: 0;
        padding-top: 1px;
        margin-bottom: -1px;
        width: auto;
        height: auto;
    }
    .main.has-header {
        top: 44px;
    }
    .main.has-footer {
        bottom: 47px;
    }
    • HTML

    <body>
        <header><header>
        <p class="main"></p>
        <footer></footer>
    </body>

    reply
    0
  • PHPz

    PHPz2017-04-10 15:12:43

    position:fixed

    reply
    0
  • Cancelreply