jQuery居中元素scrollleft计算方法示例
本文实例讲述了jQuery居中元素scrollleft计算方法。分享给大家供大家参考,具体如下:
如果需要将某个元素在可以滚动元素(scroll)中设置为居中计算方法为:
需要的scrollleft+普通居中时候的offsetLeft
=当前的scrollleft+当前元素的offsetLeft
=固定的当前元素在整个滚动条中距离左边的位置
DEMO示例:
<!DOCTYPEhtml> <htmllang="en"> <head> <metacharset="UTF-8"> <title></title> <scriptsrc="jquery.js"></script> <style> ul,li{ padding:0px; margin:0px; list-style:none; } ul{ width:1000000px; } li{ height:100px; float:left; border:1pxsolidred; } li.selected{ background-color:yellow;; } </style> </head> <body> <divclass="container"id="J_container" style="width:200px;height:100px;border:1pxsolidgray;overflow-x:scroll;overflow-y:hidden;"> <ul> <li>测试1</li> <li>测试1</li> <li>测试1</li> <li>测试1</li> <li>测试1</li> <li>测试1</li> <li>测试1</li> <liclass="selected">请将我居中</li> <li>测试1</li> <li>测试1</li> </ul> </div> <script> $(function(){ varitem=$(".selected"); varcontainer=$("#J_container"); varitemOffset=item.offset(); varitemOffsetLeft=itemOffset.left+container.scrollLeft(); varcenterLeft=(container.width()-item.width())/2; container.scrollLeft(itemOffsetLeft-centerLeft); }) </script> </body> </html>
更多关于jQuery相关内容感兴趣的读者可查看本站专题:《jQuery常用插件及用法总结》、《jQuery扩展技巧总结》、《jQuery切换特效与技巧总结》、《jQuery遍历算法与技巧总结》、《jQuery常见经典特效汇总》、《jQuery动画与特效用法总结》及《jquery选择器用法总结》
希望本文所述对大家jQuery程序设计有所帮助。