开发者

Track position on click

开发者 https://www.devze.com 2023-03-08 21:57 出处:网络
How can I track what position have I clicked wit开发者_Python百科hin an element in percent? Basicly, it\'s for a slider... And I want to track the position where to move the needle (CSSleft property

How can I track what position have I clicked wit开发者_Python百科hin an element in percent?

Basicly, it's for a slider... And I want to track the position where to move the needle (CSS left property in %) once the slider has been clicked.


Try this:

<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>


Managed to do this with:

$('#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.
});
0

精彩评论

暂无评论...
验证码 换一张
取 消