如何获取光标位置的百分比?到目前为止我试过了。
$(".outter").click(function(e) {
var perc = e.offsetX / $(this).width() * 100;
if (perc > 100)
perc = 100;
$(this).children(".progress").css("width", perc + "%");
});
$(".outter").dblclick(function(e) {
$(this).children(".progress").css("width", "100%");
});
.outter {
display: inline-block;
width: 33.33%;
box-sizing: border-box;
border: 2px solid black;
padding: 10px;
position: relative;
}
.outter > .content {
position: relative;
z-index: 2;
}
.outter > .progress {
position: absolute;
top: 0;
left: 0;
background-color: #29B6AC;
height: 100%;
width: 50%;
z-index: 1;
transition: all .3s ease;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="outter">
<div class="content">
Some content...
</div>
<div class="progress"></div>
</div>
我的问题是,perc
中的值不正确。在大约 50% 的中间,似乎还可以。但是,如果您单击大约 10% 或 90%,您会看到背景栏不会停在您的光标位置。我做错了什么?
最佳答案
.outter
div 的 padding
为 10px
,因为您使用的是 jquery 的 .width()
不包括这 20 个像素。
您可以去掉填充,也可以使用 .outerWidth()
以获得正确的尺寸。
关于javascript - jquery获取元素中鼠标点击百分比的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39324921/