【发布时间】:2015-01-27 14:34:03
【问题描述】:
有点令人困惑的标题,但问题是我们可以从.animate 内的百分比中提取像素吗?我在下面创建了一个示例。
$(document).ready(function() {
// Set the percentage off
loading();
});
function loading() {
var num = 0;
for (i = 0; i <= 100; i++) {
setTimeout(function() {
$('.follower').animate({
left: num + "%"
}, 40, "linear");
num++;
}, i * 50);
};
}
.track {
width: 90%;
height: 40px;
background: #999;
border-radius: 10px;
margin: 0 auto;
position: relative;
}
.follower {
width: 60px;
height: 20px;
border: 1px solid;
border-radius: 10px;
background: #222;
position: absolute;
top: 54px;
left: 100%;
}
.follower:after {
content: "";
width: 0;
height: 0;
border-left: 5px solid transparent;
border-right: 5px solid transparent;
border-bottom: 8px solid #222;
position: absolute;
top: -8px;
left: 0;
right: 0;
margin: auto;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="track">
<div class="follower"></div>
</div>
您可以看到.follower 正在按预期工作,但我需要它上方的那个小点来开始.track 开始的地方并结束.track 结束的地方。
所以我必须将其在 jQuery 中移动的百分比的宽度占.follower 的一半,但我找不到这样做的方法。我环顾四周,有一些方法可以使用 .css 等,但使用 .animate 时没有。
在使用.animate时,我们如何在jQuery中从百分比中获取像素?
【问题讨论】:
-
transform:translateX(-50%);on.follower不是一个选项? -
@Danko 你这个小恶魔!我已经在这里坐了半个小时,想着用 CSS 解决这个问题……这从来没有出现在我的脑海中。这对我有用,但我觉得这个问题值得回答。谢谢你!
-
@Ruddy - 纯 JavaScript 解决方案怎么样?
-
@chipChocolate.py 我更喜欢 jQuery 中的答案,但如果它解决了这个问题,我总是有兴趣查看 Javascript 解决方案。它可以帮助遇到这个问题的其他人。
标签: javascript jquery css