是否可以使用普通的javascript确定用户点击进度条的值/位置?
目前,我可以检测到元素上的点击,但只能获取栏的当前位置,与用户的点击无关.
http://jsfiddle.net/bobbyrne01/r9pm5Lzw/
HTML
<progress id="progressBar" value="0.5" max="1"></progress>
JS
document.getElementById('progressBar').addEventListener('click', function () {
alert('Current position: ' + document.getElementById('progressBar').position);
alert('Current value: ' + document.getElementById('progressBar').value);
});
解决方法:
你可以得到你在元素里面点击的坐标,如下所示:
只需从点击页面的坐标中减去元素的偏移位置即可.
document.getElementById('progressBar').addEventListener('click', function (e) {
var x = e.pageX - this.offsetLeft, // or e.offsetX (less support, though)
y = e.pageY - this.offsetTop, // or e.offsetY
clickedValue = x * this.max / this.offsetWidth;
console.log(x, y);
});
如果要确定click事件是否发生在值范围内,则必须将单击的值(与元素的宽度相关)与progress元素上设置的value属性进行比较:
document.getElementById('progressBar').addEventListener('click', function (e) {
var x = e.pageX - this.offsetLeft, // or e.offsetX (less support, though)
y = e.pageY - this.offsetTop, // or e.offsetY
clickedValue = x * this.max / this.offsetWidth,
isClicked = clickedValue <= this.value;
if (isClicked) {
alert('You clicked within the value range at: ' + clickedValue);
}
});
<p>Click within the grey range</p>
<progress id="progressBar" value="5" max="10"></progress>