【问题标题】:How to change a scrolling element behavior on resize? (HTML, CSS, JavaScript) [duplicate]如何在调整大小时更改滚动元素的行为? (HTML、CSS、JavaScript)[重复]
【发布时间】:2016-04-19 04:43:15
【问题描述】:

目前,如果我的网页上的滚动 div 垂直变小,内容会固定在 div 的顶部,而之前位于 div 底部的内容会被隐藏。

我希望它朝相反的方向工作:当 div 调整大小时,内容保持固定在底部边框,而之前位于顶部的内容会折叠。

您可以将其想象为您手机上的典型即时通讯应用。当您输入文本并且输入框变大时,它会导致显示先前消息的区域变小,但是当这种情况发生时,内容会保持固定在底部边框。

如何在 HTML/CSS/JavaScript 中实现这一点?

【问题讨论】:

  • 贴一个 jsfiddle 或者一些代码什么的...
  • 你可能想使用固定定位,但如果你想要一个具体的答案,你需要发布代码。

标签: javascript jquery html css


【解决方案1】:

这可以使用 CSS 来完成,正如我在 this answer 中展示的那样。

这是实现它的代码部分。

html, body { height:100%; margin:0; padding:0; }

.chat-window{
  display:flex;
  flex-direction:column;
  height:100%;
}
.chat-messages{
  flex: 1;
  height:100%;
  overflow: auto;
  display: flex;
  flex-direction: column-reverse;
}

/* begin - fix for hidden scrollbar in IE/Edge/Firefox */
.chat-messages-text{ overflow: auto; }
@media screen and (-webkit-min-device-pixel-ratio:0) {
  .chat-messages-text{ overflow: visible; }
  /*  reset Edge as it identifies itself as webkit  */
  @supports (-ms-accelerator:true) { .chat-messages-text{ overflow: auto; } }
}
<div class="chat-window">
  <div class="chat-messages">
    <div class="chat-messages-text" id="messages">
      Long long content 1!<br/>
      Long long content 2!<br/>
      Long long content 3!<br/>
      Long long content 4!<br/>
      Long long content 5!<br/>
      Long long content 1!<br/>
      Long long content 2!<br/>
      Long long content 3!<br/>
      Long long content 4!<br/>
      Long long content 5!<br/>
      Long long content 1!<br/>
      Long long content 2!<br/>
      Long long content 3!<br/>
      Long long content 4!<br/>
      Long long content 5!<br/>
      Long long content 1!<br/>
      Long long content 2!<br/>
      Long long content 3!<br/>
      Long long content 4!<br/>
      Long long content 5!<br/>
      Long long content 1!<br/>
      Long long content 2!<br/>
      Long long content 3!<br/>
      Long long content 4!<br/>
      Long long content 5!<br/>
    </div>
  </div>
</div>

【讨论】:

  • 这正是我所需要的!非常感谢!
【解决方案2】:

据我所知,到目前为止,仅靠 CSS 无法满足您的要求。很好,LGSon!我应该想到的。 :)

我添加了CSSHTML 只是为了演示该行为,但您实际上并不需要其中的大部分内容。您可能想要的是:

  • JavaScript/jQuery 代码
  • 在您希望底部滚动的元素上添加scrollMeDown 类。

显然,它们需要垂直溢出才能使其工作(设置固定的heightmax-heightoverflow-y:auto|scroll)。

两种解决方案在窗口loadresize 事件上向下滚动任何具有scrollMeDown 类的垂直溢出元素。

使用 JavaScript:

var scrollMeDown = function(el) {
      el.scrollTop = el.scrollHeight;
    }, 
    scrollAllDown = function() {
      var elements = document.querySelectorAll('.scrollMeDown');
      for (i = 0; i < elements.length; i++) {
        scrollMeDown(elements[i]);
      }
    };
window.onresize = function() {
  scrollAllDown();
}
window.onload = function() {
  scrollAllDown();
}
body {
   margin: 0;
   padding: 0;
 }
 
 .container {
   margin: 0;
   padding: 0;
   display: flex;
   box-sizing: border-box;
   align-content: stretch;
 }
 
 .scrollMeDown {
   max-height: 100vh;
   overflow-y: auto;

   flex: 0 1 19em;
   max-width: 50vw;
   padding: 0 1em;
   box-sizing: border-box;
   margin: 0;
 }
<div class="container">
  <div class="scrollMeDown">
    <p>Try-hard fap health goth put a bird on it, wayfarers slow-carb taxidermy tofu bitters pabst synth street art narwhal. Everyday carry neutra drinking vinegar kickstarter tote bag. +1 mustache selvage mixtape kale chips mlkshk. Helvetica iPhone yuccie 90's VHS, kogi kickstarter authentic quinoa umami. Narwhal pour-over bushwick migas. Cornhole ennui post-ironic everyday carry helvetica. Kitsch 3 wolf moon retro, fashion axe sartorial YOLO williamsburg.</p>
    <p>Dreamcatcher you probably haven't heard of them +1, chartreuse mixtape fingerstache banh mi sustainable yuccie pitchfork. Vice hella health goth, kogi marfa brunch cray small batch semiotics authentic hammock whatever pug trust fund. Raw denim gluten-free taxidermy scenester butcher, yr kombucha ennui pop-up roof party bicycle rights. Intelligentsia four loko viral, ethical chartreuse shabby chic mumblecore gastropub. 90's squid biodiesel direct trade bitters twee. Tilde DIY tousled green juice fanny pack, quinoa roof party kickstarter. Thundercats pork belly chambray stumptown chillwave, shabby chic ramps cardigan.</p>
  </div>
  <div class="scrollMeDown">
    <p>Try-hard fap health goth put a bird on it, wayfarers slow-carb taxidermy tofu bitters pabst synth street art narwhal. Everyday carry neutra drinking vinegar kickstarter tote bag. +1 mustache selvage mixtape kale chips mlkshk. Helvetica iPhone yuccie 90's VHS, kogi kickstarter authentic quinoa umami. Narwhal pour-over bushwick migas. Cornhole ennui post-ironic everyday carry helvetica. Kitsch 3 wolf moon retro, fashion axe sartorial YOLO williamsburg.</p>
    <p>Dreamcatcher you probably haven't heard of them +1, chartreuse mixtape fingerstache banh mi sustainable yuccie pitchfork. Vice hella health goth, kogi marfa brunch cray small batch semiotics authentic hammock whatever pug trust fund. Raw denim gluten-free taxidermy scenester butcher, yr kombucha ennui pop-up roof party bicycle rights. Intelligentsia four loko viral, ethical chartreuse shabby chic mumblecore gastropub. 90's squid biodiesel direct trade bitters twee. Tilde DIY tousled green juice fanny pack, quinoa roof party kickstarter. Thundercats pork belly chambray stumptown chillwave, shabby chic ramps cardigan.</p>
    <p>Pitchfork semiotics 90's, twee sartorial fingerstache slow-carb mixtape typewriter narwhal shoreditch godard. Beard yuccie green juice heirloom, deep v VHS austin normcore ethical organic health goth. Pickled literally messenger bag tumblr +1 crucifix. Forage green juice actually semiotics fashion axe, marfa chambray hashtag readymade. Franzen swag leggings, irony kogi gochujang art party. Cronut pork belly intelligentsia XOXO, gochujang ethical sriracha artisan squid. Tousled church-key offal flexitarian retro kitsch.</p>
    <p>Knausgaard bushwick fap, normcore cronut sustainable beard portland shabby chic quinoa semiotics yr cliche microdosing lo-fi. Kale chips kitsch mumblecore YOLO quinoa, DIY twee artisan authentic. Franzen +1 pinterest, godard slow-carb ramps cornhole ennui occupy butcher ugh PBR&B readymade pour-over. Echo park tacos health goth williamsburg mlkshk, umami viral fap tousled. Mixtape plaid etsy authentic, paleo blog forage gastropub. Master cleanse mixtape brunch chartreuse pabst dreamcatcher craft beer, truffaut slow-carb VHS 8-bit williamsburg beard swag shabby chic. Flannel next level lumbersexual, heirloom lo-fi gochujang tofu.</p>
  </div>
</div>

如果您需要它在其他事件上运行,只需在您的事件上调用以下任何函数:

  • scrollAllDown() - 向下滚动所有 .scrollMeDown 元素
  • scrollMeDown(DOMElement) - 向下滚动作为参数传递的元素

使用 jQuery:

$.fn.extend({
  scrollMeDown: function() {
    $(this).scrollTop($(this).prop('scrollHeight'));
  },
  scrollAllDown: function(selector) {
    $(selector).each(function(){
      $(this).scrollMeDown();
    })
  }
})

$(window).on('load resize', function() {
  $().scrollAllDown('.scrollMeDown');
});
body {
   margin: 0;
   padding: 0;
 }
 
 .container {
   margin: 0;
   padding: 0;
   display: flex;
   box-sizing: border-box;
   align-content: stretch;
 }
 
 .scrollMeDown {
   max-height: 100vh;
   overflow-y: auto;

   flex: 0 1 19em;
   max-width: 50vw;
   padding: 0 1em;
   box-sizing: border-box;
   margin: 0;
 }
<div class="container">
<div class="scrollMeDown">
  <p>Try-hard fap health goth put a bird on it, wayfarers slow-carb taxidermy tofu bitters pabst synth street art narwhal. Everyday carry neutra drinking vinegar kickstarter tote bag. +1 mustache selvage mixtape kale chips mlkshk. Helvetica iPhone yuccie 90's VHS, kogi kickstarter authentic quinoa umami. Narwhal pour-over bushwick migas. Cornhole ennui post-ironic everyday carry helvetica. Kitsch 3 wolf moon retro, fashion axe sartorial YOLO williamsburg.</p>
  <p>Dreamcatcher you probably haven't heard of them +1, chartreuse mixtape fingerstache banh mi sustainable yuccie pitchfork. Vice hella health goth, kogi marfa brunch cray small batch semiotics authentic hammock whatever pug trust fund. Raw denim gluten-free taxidermy scenester butcher, yr kombucha ennui pop-up roof party bicycle rights. Intelligentsia four loko viral, ethical chartreuse shabby chic mumblecore gastropub. 90's squid biodiesel direct trade bitters twee. Tilde DIY tousled green juice fanny pack, quinoa roof party kickstarter. Thundercats pork belly chambray stumptown chillwave, shabby chic ramps cardigan.</p>
</div>
<div class="scrollMeDown">
  <p>Try-hard fap health goth put a bird on it, wayfarers slow-carb taxidermy tofu bitters pabst synth street art narwhal. Everyday carry neutra drinking vinegar kickstarter tote bag. +1 mustache selvage mixtape kale chips mlkshk. Helvetica iPhone yuccie 90's VHS, kogi kickstarter authentic quinoa umami. Narwhal pour-over bushwick migas. Cornhole ennui post-ironic everyday carry helvetica. Kitsch 3 wolf moon retro, fashion axe sartorial YOLO williamsburg.</p>
  <p>Dreamcatcher you probably haven't heard of them +1, chartreuse mixtape fingerstache banh mi sustainable yuccie pitchfork. Vice hella health goth, kogi marfa brunch cray small batch semiotics authentic hammock whatever pug trust fund. Raw denim gluten-free taxidermy scenester butcher, yr kombucha ennui pop-up roof party bicycle rights. Intelligentsia four loko viral, ethical chartreuse shabby chic mumblecore gastropub. 90's squid biodiesel direct trade bitters twee. Tilde DIY tousled green juice fanny pack, quinoa roof party kickstarter. Thundercats pork belly chambray stumptown chillwave, shabby chic ramps cardigan.</p>
  <p>Pitchfork semiotics 90's, twee sartorial fingerstache slow-carb mixtape typewriter narwhal shoreditch godard. Beard yuccie green juice heirloom, deep v VHS austin normcore ethical organic health goth. Pickled literally messenger bag tumblr +1 crucifix. Forage green juice actually semiotics fashion axe, marfa chambray hashtag readymade. Franzen swag leggings, irony kogi gochujang art party. Cronut pork belly intelligentsia XOXO, gochujang ethical sriracha artisan squid. Tousled church-key offal flexitarian retro kitsch.</p>
  <p>Knausgaard bushwick fap, normcore cronut sustainable beard portland shabby chic quinoa semiotics yr cliche microdosing lo-fi. Kale chips kitsch mumblecore YOLO quinoa, DIY twee artisan authentic. Franzen +1 pinterest, godard slow-carb ramps cornhole ennui occupy butcher ugh PBR&B readymade pour-over. Echo park tacos health goth williamsburg mlkshk, umami viral fap tousled. Mixtape plaid etsy authentic, paleo blog forage gastropub. Master cleanse mixtape brunch chartreuse pabst dreamcatcher craft beer, truffaut slow-carb VHS 8-bit williamsburg beard swag shabby chic. Flannel next level lumbersexual, heirloom lo-fi gochujang tofu.</p>
</div>
  </div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

这会将.scrollMeDown().scrollAllDown() 注册为jQuery 函数。具有能够在文档的仅部分(sectionSelector - 使用任何 CSS 选择器)上运行 .scrollAllDown() 的优势,对于 toBeScrolledSelector 选择的所有子项(使用任何 CSS 选择器),使用以下构造:

$('sectionSelector').scrollAllDown('toBeScrolledSelector')

如果您想在所有文档上使用它,则不需要sectionSelector,只需运行

$().scrollAllDown('toBeScrolledSelector')

【讨论】:

  • 谢谢 .. 我给 +1 一个完整的脚本版本(包括调整大小)
【解决方案3】:

试着从这里挽救你想要的东西

https://jsfiddle.net/uakxcws8/

点击页面底部的“点击”链接重新调整 div 的大小

核心方面是重置滚动顶部(jquery)

var newH = 300; // the value by which the div was shrunk   
var x = $("#swindow").scrollTop()+newH+100 ;
$("#swindow").scrollTop(x);

常数 100 似乎是准确定位内容所必需的。

在 GC 和 FF 中测试了这段代码

    <script>
    function init(){
         $("#btn").click(function(){
             var newH = 300;
             $("#swindow").css("height",newH+"px");
             var x = $("#swindow").scrollTop()+newH+100 ;
             $("#swindow").scrollTop(x);
         }); 
    }

    init();
    </script>
.
.
.    
    <div style="width: 800px; height:800px; border: solid 1px #000; position:relative;">
                    <div style="width:300px; height:700px; bottom:0; border: solid 1px #000; overflow:scroll; position:absolute;" id="swindow">
                        <div>
                           <p>...............</p>
                        </div>    
                    </div>
                </div>
                <a id="btn" style="cursor:pointer;">Click</a>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-05-02
    • 2016-05-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-10
    • 1970-01-01
    相关资源
    最近更新 更多