2011-05-29 113 views
0

如何跟踪我在某个元素中点击了多少位置?点击跟踪位置

基本上,它是一个滑块......并且我想跟踪滑块被点击后移动针的位置(CSS left属性%)。

回答

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. 
}); 
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> 
+0

咦,这是接近,但值是很多大于100,而当浏览器大小的变化,从700 +到900+。这不完全是'div'中的位置,其宽度范围从100px到150px(实际上它是100%宽度'div') – jolt 2011-05-29 16:56:18