如何跟踪我在元素中按百分比单击的位置?
基本上,它是一个滑块......我想跟踪滑块被点击后移动针的位置(%left
属性)。
答案 0 :(得分:1)
试试这个:
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
jQuery(document).ready(function(){
$("#special").click(function(e){
var xP = e.pageX * 100 / $(e.target).width();
var yP = e.pageY * 100 / $(e.target).height();
$('#status2').html(xP +', '+ yP);
});
})
</script>
<body>
<h2 id="status2">
0, 0
</h2>
<div style="width: 100px; height: 100px; background:#ccc;" id="special">
Click me anywhere!
</div>
</body>
</html>
答案 1 :(得分:0)
通过以下方式管理:
$('#song-seeker').click(function(e){
var offset = $(this).offset(); // somehow this.offsetLeft didn't work
var x = Math.floor(e.pageX - offset.left); // calculates pixel value of position clicked within element
x = Math.floor(x * 100 / $(this).width()); // transform to % value based on full clicked elements width
// Math.floor() used to prepare values with 0 values behind comma, therefore, CSS safe.
});