Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
383 views
in Technique[技术] by (71.8m points)

javascript - 确定进度条上的点击位置?(Determine click position on progress bar?)

Is it possible to determine the value/position of a user's click on a progress bar using plain javascript?(是否可以使用普通的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/(http://jsfiddle.net/bobbyrne01/r9pm5Lzw/) HTML(的HTML) <progress id="progressBar" value="0.5" max="1"></progress> JS(JS) document.getElementById('progressBar').addEventListener('click', function () { alert('Current position: ' + document.getElementById('progressBar').position); alert('Current value: ' + document.getElementById('progressBar').value); });   ask by bobbyrne01 translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.(只需从单击页面的坐标中减去元素的偏移位置即可。) Updated Example(更新示例) 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); }); 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:(如果要确定click事件是否在值范围内发生,则必须将clicked值(相对于元素的宽度)与progress元素上设置的value属性进行比较:) Example Here(这里的例子) 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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...