js如何实现调节音量滑块

时间:2020-03-18  编辑:

首先,我们来看一下效果:

1584414373409176.png

(推荐教程:javascript教程

html代码:

1

2

3

4

5

6

7

8

<body>

<div class="all">

<p>当前位置0%</p>

<div class="bar">

<div class="box"></div>

</div>

</div>

</body>

css代码:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

<style>

.all {

width: 500px;

height: 80px;

margin: 100px auto;

position: relative;

}

 

.bar {

width: 500px;

height: 20px;

border-radius: 10px;

background: #aaa;

position: absolute;

top: 0;

bottom: 0;

left: 0;

right: 0;

margin: auto;

cursor: pointer;

}

 

.box {

width: 30px;

height: 30px;

background: #000;

position: absolute;

bottom: 0;

top: 0;

margin: auto 0;

border-radius: 50%;

cursor: pointer;

transition: left 0.1s linear 0s;

}

</style>

js代码:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

<script>

var box = document.getElementsByClassName('box')[0]

var bar = document.getElementsByClassName('bar')[0]

var all = document.getElementsByClassName('all')[0]

var p = document.getElementsByTagName('p')[0]

var cha = bar.offsetWidth - box.offsetWidth

box.onmousedown = function (ev) {

let boxL = box.offsetLeft

let e = ev || window.event //兼容性

let mouseX = e.clientX //鼠标按下的位置

window.onmousemove = function (ev) {

let e = ev || window.event

let moveL = e.clientX - mouseX //鼠标移动的距离

let newL = boxL + moveL //left值

// 判断最大值和最小值

if (newL < 0) {

newL = 0

}

if (newL >= cha) {

newL = cha

}

// 改变left值

box.style.left = newL + 'px'

// 计算比例

let bili = newL / cha * 100

p.innerHTML = '当前位置' + Math.ceil(bili) + '%'

return false //取消默认事件

}

window.onmouseup = function () {

window.onmousemove = false //解绑移动事件

return false

}

return false

};

// 点击音量条

bar.onclick = function (ev) {

let left = ev.clientX - all.offsetLeft - box.offsetWidth / 2

if (left < 0) {

left = 0

}

if (left >= cha) {

left = cha

}

box.style.left = left + 'px'

let bili = left / cha * 100

p.innerHTML = '当前位置' + Math.ceil(bili) + '%'

console.log(left)

return false

}

</script>

以上就是js如何实现调节音量滑块的详细内容,更多请关注php知识-学习天地 www.lxywzjs.com其它相关文章!

分享至:

分享到QQ空间 分享到朋友社区 新浪微博分享

SITE MAP

扫一扫,加微信
扫一扫,关注公众号