Today, there is a problem in the mobile event of writing a custom scroll bar with native JS. The scene is to click a div and move the div (ID: scroll_box) to make the scroll bar of the div beyond the fixed height move with it. The general normal logic is as follows:
let oScrollBox = document.getElementById('scroll_box'); oScrollBox.onmousedown = function(e) { let event1 = e || event; let positionY = event1.clientY - this.offsetTop; document.onmousemove = function(ev) { let event2 = ev || event; var divY = event2.clientY - positionY; oScrollBox.style.top = divY + 'px'; } document.onmouseup = function() { document.onmousemove = null; }; }
At this time, the error will be reported.
The event2 = ev || event; in the document.onmousemove method causes the error here, because the event variable is already used in the let event1 = e || event; above, so an error is reported. The solution is to write document.onmousemove into a separate In the method, so that you can avoid the variable duplication problem, the code is as follows:
oScrollBox.onmousedown = function(e) { let event1 = e || event; let positionY = event1.clientY - this.offsetTop; document.onmousemove = function(ev) { mouseMove(oScrollBox,ev,positionY); } document.onmouseup = function() { document.onmousemove = null; } }; function mouseMove(obj,e,positionY) { let event2 = e || event; var divY = event2.clientY - positionY; obj.style.top = divY + 'px'; }
This can be solved perfectly!
Similar Posts:
- ”Cannot read property ‘addEventListener’ of null“
- Four ways to solve selenium’s error “element is not clickable at point…”
- The Difference between Document.ready and Window.onload
- event.srcElement And event.target The difference between
- The applet reports an error thirdscripterror DateValue is not defined;
- How to Solve Error: Cannot set property ‘onclick’ of null
- Typeerror: error # 1009: the property or method referenced by an empty object cannot be accessed.
- Error in JS function referencing public page [How to Solve]
- [How to Solve] Cannot set property ‘onclick’ of null
- Syntax error reported by JavaScript function: expected expression, got ‘;’