1 /* 2 1. 浏览器在没有滚动条的时候,scrollLeft/scrollTop赋值后不会发生变化,始终是0; 3 2. scrollLeft,scrollTop为负数值时会报错 4 */ 5 var scroll = function (elm) { 6 var elms = elm ? [elm] : [document.documentElement, document.body], 7 scrollX = false, 8 scrollY = false, 9 i, len, tmp, obj; 10 11 for (i = 0, len = elms.length; i < len; i++) { 12 obj = elms[i]; 13 14 //Test horizontal scroll 15 tmp = obj.scrollLeft; 16 obj.scrollLeft += (tmp > 0) ? -1 : 1; 17 obj.scrollLeft !== tmp && (scrollX = scrollX || true); 18 obj.scrollLeft = tmp; 19 20 //Test vertical scroll 21 tmp = obj.scrollTop; 22 obj.scrollTop += (tmp > 0) ? -1 : 1; 23 obj.scrollTop !== tmp && (scrollY = scrollY || true); 24 obj.scrollTop = tmp; 25 } 26 27 return { 28 ‘isScrollX‘: scrollX, 29 ‘isScrollY‘: scrollY 30 }; 31 };
1 /* 2 1. 向页面插入一个看不到的元素,并设置它的宽度w,自身显示滚动条; 3 2. 浏览器滚动条的宽度 = w - 它的clientWidth 4 */ 5 var getScrollWidth = function () { 6 var testNode, tmp; 7 8 testNode = document.createElement(‘div‘); 9 testNode.style.cssText = "position:absolute;width:50px;height:50px;top:-1000px;overflow-y:scroll;"; 10 document.body.appendChild(testNode); 11 12 tmp = testNode.clientWidth; 13 document.body.removeChild(testNode); 14 return 50 - tmp; 15 };
总结项目中经常用到的通用工具函数。
原文:http://www.cnblogs.com/zhouwenhong/p/3870277.html