This article describes the calculation method of the jQuery centering element scrollleft. Share it for your reference, as follows:
If you need to set an element to center in a scrollable element (scroll) calculation method is:
Need scrollleft + offsetLeft when normal centering
= current scrollleft+offsetLeft of current element
= Fixed current element at the left position in the entire scroll bar
DEMO example:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title></title> <script src=""></script> <style> ul, li { padding: 0px; margin: 0px; list-style: none; } ul { width: 1000000px; } li { height: 100px; float: left; border: 1px solid red; } { background-color: yellow;; } </style> </head> <body> <div class="container" style="width: 200px;height: 100px;border:1px solid gray; overflow-x: scroll; overflow-y: hidden;"> <ul> <li>test1</li> <li>test1</li> <li>test1</li> <li>test1</li> <li>test1</li> <li>test1</li> <li>test1</li> <li class="selected">Please center me</li> <li>test1</li> <li>test1</li> </ul> </div> <script> $(function () { var item = $(".selected"); var container = $("#J_container"); var itemOffset = (); var itemOffsetLeft = + (); var centerLeft = ( () - ()) / 2; (itemOffsetLeft - centerLeft); }) </script> </body> </html>
For more information about jQuery, please visit the special topic of this site:Summary of commonly used plug-ins and usages of jQuery》、《Summary of jQuery extension skills》、《Summary of jQuery switching effects and skills》、《Summary of jQuery traversal algorithm and skills》、《Summary of common classic effects of jQuery》、《Summary of jQuery animation and special effects usage"and"Summary of jquery selector usage》
I hope this article will be helpful to everyone's jQuery programming.