html input range,html - HTML5 input type range show range value - Stack Overflow

本文介绍了一种JavaScript实现的解决方案,该方案允许将number输入和range输入进行联动,当一个元素的值改变时,另一个元素会自动调整。这个库不仅适用于新的DOM元素,还支持后期添加到页面上的元素,并且在Chrome, Firefox, Edge和IE11等浏览器上正常工作。通过设置source属性,可以指定要监听的输入源。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

I have a solution that involves (Vanilla) JavaScript, but only as a library. You habe to include it once and then all you need to do is set the appropriate source attribute of the number inputs.

The source attribute should be the querySelectorAll selector of the range input you want to listen to.

It even works with selectcs. And it works with multiple listeners. And it works in the other direction: change the number input and the range input will adjust. And it will work on elements added later onto the page (check https://codepen.io/HerrSerker/pen/JzaVQg for that)

Tested in Chrome, Firefox, Edge and IE11

;(function(){

function emit(target, name) {

var event

if (document.createEvent) {

event = document.createEvent("HTMLEvents");

event.initEvent(name, true, true);

} else {

event = document.createEventObject();

event.eventType = name;

}

event.eventName = name;

if (document.createEvent) {

target.dispatchEvent(event);

} else {

target.fireEvent("on" + event.eventType, event);

}

}

var outputsSelector = "input[type=number][source],select[source]";

function onChange(e) {

var outputs = document.querySelectorAll(outputsSelector)

for (var index = 0; index < outputs.length; index++) {

var item = outputs[index]

var source = document.querySelector(item.getAttribute('source'));

if (source) {

if (item === e.target) {

source.value = item.value

emit(source, 'input')

emit(source, 'change')

}

if (source === e.target) {

item.value = source.value

}

}

}

}

document.addEventListener('change', onChange)

document.addEventListener('input', onChange)

}());

0

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值