Home > Article > Web Front-end > How to set scroll bar height in javascript
How to set the height of the scroll bar in javascript: first get the height of the node in front of the currently selected li; then subtract half of the height of ul and set it to the scrollTop of ul, and set the scroll bar in the middle position.
The operating environment of this article: windows7 system, javascript version 1.8.5, Dell G3 computer.
JavaScript dynamically sets the scroll bar height
The situation encountered at work is as follows: a ul tag, which contains many li tags, one of which represents the initialization of the selected 5d7e5b63bb2c2f21c9ee5b2d95d6d3b225edfb22a4f469ecb59f1190150159c6.
If ul has a height set, such as the ul style below, and there are many li sub-tags, the selected li will be submerged under the scroll bar.
<ul id="ul_module" style="height:180px; overflow-y:scroll;"> <li>...</li> <li>...</li> <li>...</li> <li>...</li> <li>...</li> <li>...</li> <li>...</li> <li>...</li> <li>...</li> <li>000</li> <li>111</li> <li>222</li> <li>333</li> <li>444</li> <li>555</li> <li>666</li> <li>777</li> <li>888</li> <li class="li-on">999</li> <li>...</li> <li>...</li> <li>...</li> <li>...</li> <li>...</li> <li>...</li> <li>...</li> <li>...</li> <li>...</li> </ul>
What you need to do is to move the selected li tag into the visible area, and you can dynamically set the height of the scroll bar through js.
The details are as follows: get the height of the node in front of the currently selected li, then subtract half of the height of ul and set it to the scrollTop of ul. Basically, you can set the scroll bar in the middle position.
var ul_module = $('#ul_module'); var ul_height = ul_module.height(); var seleted_li = ul_module.find('.li-on'); if(seleted_li.length) { var height = seleted_li.height(); var prevCount = seleted_li.prevAll().length; ul_module.scrollTop(height * prevCount - ul_height/2); }
【Recommended learning: javascript advanced tutorial】
The above is the detailed content of How to set scroll bar height in javascript. For more information, please follow other related articles on the PHP Chinese website!