简体   繁体   English

添加新项目时如何自动按下滚动条

[英]How to automatically push scroll-bar when new item was added

Please check out this fiddle . 请检查这个小提琴 If you add items to the #scroll div, the scroll-bar is fixed - it just stays at the "beginning". 如果您将项目添加到#scroll div中,则滚动条是固定的-它只是停留在“开始”位置。 What I want to achieve is to move scroll-bar automatically when a new item is being appended to the parent. 我要实现的是在将新项添加到父项时自动移动滚动条。 Is it possible to do this via magic of CSS? 是否可以通过CSS魔术来做到这一点? :)) Or only JS gonna solve it? :))还是只有JS才能解决?

Code: 码:

HTML HTML

<div id="scroll">
   <div class="addElement">FIRST</div>
   <div class="addElement"></div>
   <div class="addElement">LAST</div>
</div>
<button id="add">ADD NEW ELEMENT</button>

CSS CSS

#scroll {
overflow: auto;
overflow-y: hidden;
width: 200px;
height: 150px;
background: red;
position: relative;
display: flex;
align-items: center;
}

.addElement {
  margin: 5px;
  height: 60px;
  width: 55px;
  background: green;
  flex: 0 0 auto;
}

JS JS

var scroll = $('#scroll');
var addButton = $('#add');

var item = 1;
addButton.click(function() {
    scroll.append(`<div class="addElement">ITEM ${item}</div>`);
  item++;
});

Thank you for any suggestion! 感谢您的任何建议!

I've updated your fiddle to demonstrate a jQuery method of doing this: 我已经更新了您的小提琴,以演示执行此操作的jQuery方法:

https://jsfiddle.net/93gz3u1L/11/ https://jsfiddle.net/93gz3u1L/11/

I just added the following using scrollLeft (You can remove the animation if needed): 我只是使用scrollLeft添加了以下内容(您可以根据需要删除动画):

addButton.click(function() {
    scroll.append(`<div class="addElement">ITEM ${item}</div>`);
  item++;
  scroll.animate({
    scrollLeft: scroll.get()[0].scrollWidth
  });
});

You can use the css Direction property, setted to rtf! 您可以使用设置为rtf的css Direction属性! (right to left) (右到左)

 #scroll {
    ...
    direction: rtl;
}

but you will need to prepend the elem instead of append it to the parent. 但您需要将elem放在前面 ,而不是将其附加到父元素。

https://jsfiddle.net/k6Lhv3u6/1/ https://jsfiddle.net/k6Lhv3u6/1/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM