检测div中单击的水平位置

时间:2012-12-29 15:01:31

标签: javascript css

当我点击流式条时,将从浏览器窗口的左边缘检测到位置,但必须从此 demo中的#progressBar div的左边缘检测到位置。因此,由于#progressBar div位于left: 200px;,因此在点击的水平位置添加了200px。

我的简单检测功能:

function point_it(e){
      var x=e.clientX; 
      var seekSecond = Math.floor((x/1100) * ytplayer.getDuration()); //1100 is width of the progress bar 
      seekTo(seekSecond);
      document.getElementById("xPos").innerHTML=x;
    }

式:

    #progressBar{
position: relative;
top: 400px;
left: 200px;
width: 1100px;
height: 4px;
border: 2px solid gray;
margin: 10px;
z-index: 8;
}


#elapsedBar{
position: relative;
top: -1px;
width:0px;
height:3px;
border:1px solid;
border-color: #660033;
background-color: #660033;
margin:0px;
z-index: 10;
}

#loadedBar{
position: relative;
top: 0px;
width: 0px;
height:4px;
border:1px solid;
border-color: gray;
background-color: gray;
margin:0px;
z-index: 9;
}

3 个答案:

答案 0 :(得分:1)

你可以从点击的位置减去左边的位置,我只知道jQuery这样做的方法:

// Get the "left" value
var leftPos = $("#progressBar").css("left");
// Remove "px"
var leftPos = leftPos.replace("px", "");

然后从您获得的值中减去leftPos

答案 1 :(得分:1)

只需在您的函数中使用e.offsetX而不是e.clientX

e.client...与浏览器窗口相关,e.offsett...与点击的目标元素相关。

答案 2 :(得分:1)

由于x,您必须从margin: 10px;中减去10。当点击栏的左侧时,这会使var x=e.clientX;为10。