确定进度条上的点击位置? [英] Determine click position on progress bar?

查看:210
本文介绍了确定进度条上的点击位置?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以使用纯JavaScript来确定用户点击进度条的价值/位置?

Is it possible to determine the value/position of a user's click on a progress bar using plain javascript?

当前,我可以检测到元素上的点击,但是只能获取条的当前位置,与用户的点击无关.

Currently, I can detect a click on the element but can only get the current position of the bar, not related to the user's click.

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);
});

推荐答案

您可以像这样获得在元素内单击位置的坐标:

You can get the coordinates of where you clicked inside of the element like this:

只需从点击页面的坐标中减去元素的偏移位置即可.

Just subtract the offset position of the element from the coordinate of where the page was clicked.

更新示例

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事件是否在值范围内发生,则必须将clicked值(相对于元素的宽度)与progress元素上设置的value属性进行比较:

If you want to determine whether the click event occurred within the value range, you would have to compare the clicked value (in relation to the element's width), with the the value attribute set on the progress element:

此处的示例

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>

这篇关于确定进度条上的点击位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆