如何在div的顶部和底部获取水平滚动条? [英] How can I get horizontal scrollbars at top and bottom of a div?
问题描述
因为我很肯定没有原生html或css的方式这样做,我开放使用JavaScript。显然,我可以得到一个滚动条在我的div的底部使用overflow:auto在CSS。是否有一些javascript可以克隆滚动条从底部,并将它放在div的顶部?
Since I'm pretty sure there is no native html or css way of doing this, I'm open to doing this with JavaScript. Obviously, I can get a scrollbar at the bottom of my div using overflow: auto in CSS. Is there some javascript that could "clone" the scrollbar from the bottom and place it at the top of the div? Maybe there's another way?
推荐答案
您可以在真实世界之上创建一个新的虚拟元素,获取额外的滚动条,然后将滚动条与 onscroll
事件绑定。
You could create a new dummy element above the real one, with the same amount of content width to get an extra scrollbar, then tie the scrollbars together with onscroll
events.
function DoubleScroll(element) {
var scrollbar= document.createElement('div');
scrollbar.appendChild(document.createElement('div'));
scrollbar.style.overflow= 'auto';
scrollbar.style.overflowY= 'hidden';
scrollbar.firstChild.style.width= element.scrollWidth+'px';
scrollbar.firstChild.style.paddingTop= '1px';
scrollbar.firstChild.appendChild(document.createTextNode('\xA0'));
scrollbar.onscroll= function() {
element.scrollLeft= scrollbar.scrollLeft;
};
element.onscroll= function() {
scrollbar.scrollLeft= element.scrollLeft;
};
element.parentNode.insertBefore(scrollbar, element);
}
DoubleScroll(document.getElementById('doublescroll'));
#doublescroll
{
overflow: auto; overflow-y: hidden;
}
#doublescroll p
{
margin: 0;
padding: 1em;
white-space: nowrap;
}
<div id="doublescroll">
<p>
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do
eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut
enim ad minim veniam, quis nostrud exercitation ullamco laboris
nisi ut aliquip ex ea commodo consequat.
</p>
</div>
可以改进的概念证明例如。通过轮询或侦听可能更改元素
的 scrollWidth
的事件,例如窗口调整%
长度正在使用,字体大小更改或由其他脚本驱动的内容更改。还有(像往常一样)IE选择在元素内部渲染水平滚动条,以及IE7的页面缩放问题。但这是一个开始。
This is a proof of concept that could be improved eg. by polling or listening for events that might change the scrollWidth
of element
, for example window resizes when %
lengths are in use, font size changes, or content changes driven by other scripts. There are also (as usual) issues with IE choosing to render horizontal scrollbars inside the element, and IE7's page zooming. But this is a start.
这篇关于如何在div的顶部和底部获取水平滚动条?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!