scroll по телу страницы с помощью мыши
Вложений: 1
Задача:
Есть длинная страница по горизонтали более 3000px. Необходимо скролить страницу просто хватая левой кнопкой мыши за любую точку страницы, и тянув её, аналог обычного виндовского просмотрщика изображений. Вот что я навоял (все работает, но не гладко, в некоторых моментах страница дергается, и нижний скрол теперь нельзя тягать отдельно), тут показываю только JS, и приложил txt файл полностью функциональный: <script> $( document ).ready(function() { document.captureEvents(Event.MOUSEUP|Event.MOUSEDOWN); document.onmousedown=DRAG_begindrag; document.onmouseup=DRAG_enddrag; var DRAG_lastX, DRAG_dragging; function DRAG_begindrag(e) { if (e.which == 1) { window.captureEvents(Event.MOUSEMOVE); window.onmousemove=DRAG_drag; DRAG_lastX=e.pageX; DRAG_dragging=true; return false; } else {return true;} } function DRAG_enddrag(e) { if (e.which == 1) { window.releaseEvents(Event.MOUSEMOVE); window.onmousemove=null DRAG_dragging=false; return false; } else {return true;} } function DRAG_drag(e) { if (DRAG_dragging) { s1 = e.pageX - DRAG_lastX s = window.pageXOffset - s1; window.scroll(s); DRAG_lastX = e.pageX; return false; } else {return true;} } }); </script> Помогите пожалуйста понять, почему страница дергается, и как отвязаться от нижнего скрола, чтобы он отдельно хорошо работал. |
Цитата:
|
trec, вам к врачу, у вас похоже jQuery головного мозга. Подключать целую либу ради одной функции? Про второе назначение микроскопа наверно хорошо наведаны? В IE8 работать не будет:
<!DOCTYPE html> <head> <title></title> <style> #page{ width: 3200px; height: 1000px;} </style> </head> <body> <div id="page"> This document was produced by a group operating under the 5 February 2004 W3C Patent Policy. W3C maintains a public list of any patent disclosures made in connection with the deliverables of the group; that page also includes instructions for disclosing a patent. An individual who has actual knowledge of a patent which the individual believes contains Essential Claim(s) must disclose the information in accordance with section 6 of the W3C Patent Policy. </div> <script> var dragHandler = { lastClientX: 0, start: function (e) { if (e.button == 0) { window.addEventListener('mousemove', dragHandler.drag); dragHandler.lastClientX = e.clientX; e.preventDefault(); } }, end: function (e) { if (e.button == 0) { window.removeEventListener('mousemove', dragHandler.drag); } }, drag: function (e) { var delta = e.clientX - dragHandler.lastClientX; window.scrollTo(window.scrollX - delta, window.scrollY); dragHandler.lastClientX = e.clientX; e.preventDefault(); } }; document.addEventListener('mousedown', dragHandler.start); document.addEventListener('mouseup', dragHandler.end); </script> </body> |
danik.js,
может вешать не на document а на document.body иначе обычным скролингом нельзя пользоватся |
Цитата:
Либу подключал не для этого скрипта, на странице в принципе есть jQuery. Ваше решение отличное, жаль что в IE не работает. Цитата:
Мне еще подобное решение предложили http://jsfiddle.net/z7JJg/4/, пробовал в IE, тоже работает, но увы немного тоже притормаживает. Поправка, убрал из предложенного в примере setTimeout, скрипт перестал притормаживать, теперь работает тоже гладко, и прекрасно. Всем спасибо. Для тех кто обратится к подобной проблеме, будет 2 варианта её решения. |
Исправил для работы в IE9+ и позаимствовал учет соотношения ширина документа / ширина окна
<!DOCTYPE html> <head> <title></title> <style> #page{ width: 3200px; height: 1000px;} </style> </head> <body> <div id="page"> This document was produced by a group operating under the 5 February 2004 W3C Patent Policy. W3C maintains a public list of any patent disclosures made in connection with the deliverables of the group; that page also includes instructions for disclosing a patent. An individual who has actual knowledge of a patent which the individual believes contains Essential Claim(s) must disclose the information in accordance with section 6 of the W3C Patent Policy. </div> <script> function DragHandler() { this.lastClientX = 0; this.onResize = function (e) { this.ratio = (document.body.scrollWidth - document.body.offsetWidth ) / document.body.offsetWidth; }.bind(this); this.onMouseDown = function (e) { if (e.button == 0) { window.addEventListener('mousemove', this.onMouseMove); this.lastClientX = e.clientX; e.preventDefault(); } }.bind(this); this.onMouseUp = function (e) { if (e.button == 0) { window.removeEventListener('mousemove', this.onMouseMove); } }.bind(this); this.onMouseMove = function (e) { var delta = (e.clientX - this.lastClientX) * this.ratio; window.scrollTo(window.pageXOffset - delta, window.pageYOffset); this.lastClientX = e.clientX; }.bind(this); document.body.addEventListener('mousedown', this.onMouseDown); document.addEventListener('mouseup', this.onMouseUp); window.addEventListener('resize', this.onResize); this.onResize(); } new DragHandler(); </script> </body> |
Часовой пояс GMT +3, время: 21:43. |