Get the App
SLTechnology News&Howtos  ›  Development  › 

How to realize the effect of dragging Slider with js

Shulou Source: shulou.com Published: 2022-06-03 09:27:49 09月18日 Update

This article will explain in detail how js can achieve the effect of dragging the slider. The editor thinks it is very practical, so I share it for you as a reference. I hope you can get something after reading this article.

The details are as follows

To achieve dragging the slider, first analysis, the slider can be dragged should change the coordinates of the slider in the page, then use the location to get the elements of the top and left to assign them, and then is to prepare the event, since it is a mouse drag should have mousedown,mousemove,mouseup three events, through the mousedown mouse down event to select the slider, mousemove event to drag the slider Get the top and left assigned to the slider by mouse coordinates in the visual window when dragging the slider

Specific code implementation

Document * {margin: 0; padding: 0; box-sizing: border-box;} div {width: 60px; height: 60px; background-color: coral; border-radius: 20%; position: absolute; border: 6px solid skyblue; left: 0 Top: 0;} let div = document.querySelector ('div') let x, y let fn = function (e) {/ / console.log (' hhhhhhhh') div.style.left = e.clientX-x + 'px' div.style.top = e.clientY-y +' px' if (e.clientX-x)

< 30) { div.style.left = 0 } if (e.clientY - y < 30) { div.style.top = 0 } if (e.clientX - x >

Document.documentElement.clientWidth-div.offsetWidth-30) {div.style.left = document.documentElement.clientWidth-div.offsetWidth + 'px'} if (e.clientY-y > document.documentElement.clientHeight-div.offsetHeight-30) {div.style.top = document.documentElement.clientHeight-div.offsetHeight +' px'}} div.addEventListener ('mousedown' Function (e) {x = e.offsetX y = e.offsetY document.addEventListener ('mousemove', fn)}) div.addEventListener (' mouseup', function () {document.removeEventListener ('mousemove', fn)})

Running

This is the end of the article on "how to drag the slider effect in js". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, please share it out for more people to see.

Tags: Events articles mouse effects content coordinates more good practical next code elements that is articles times knowledge pages preparation analysis reference Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Huawei macOS MySQL Shulou Technology OPPO Reno