【发布时间】:2011-03-30 03:52:56
【问题描述】:
我正在通过 JavaScript / jQuery 缩放和移动文本。我不能使用 jQuerys animate(),因为它必须淡入淡出,并且必须重复使用更多元素(最终结果:从背景“飞”,朝不同方向移动并淡出)。
我的问题:它运行不顺畅并导致相当多的 cpu 使用率。这是一个精简版:
<!DOCTYPE html>
<html>
<head>
<script class="jsbin" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<meta charset=utf-8 />
<title>JS Bin</title>
<!--[if IE]>
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<script type="text/javascript">
var steps = 300; // steps from start to finish
// the final css values
var endValueTop = 300;
var endValueLeft = 300;
var endValueFontSize = 100;
// the current css values (get encreased in doAnimation())
var currentValueTop = 100;
var currentValueLeft = 100;
var currentValueFontSize = 0;
// the added values in each step
var stepsTop = (endValueTop - currentValueTop) / steps;
var stepsLeft = (endValueLeft - currentValueLeft) / steps;
var stepsFontSize = (endValueFontSize - currentValueFontSize) / steps;
function doAnimation() {
// increase current values
currentValueTop += stepsTop;
currentValueLeft += stepsLeft;
currentValueFontSize += stepsFontSize;
// apply them
$("#hello").css({
top: currentValueTop,
left: currentValueLeft,
fontSize: currentValueFontSize
});
// restart if there are steps left
if (steps--) {
window.setTimeout(function(){
doAnimation();
}, 50);
}
}
// start the first time
doAnimation();
</script>
<style>
article, aside, figure, footer, header, hgroup,
menu, nav, section { display: block; }
body { position: relative; }
p#hello { position: absolute; top: 100px; left: 100px; font-size: 0px; }
</style>
</head>
<body>
<p id="hello">Hello World</p>
</body>
</html>
在JS BIN 上运行示例。
有什么建议吗?奖励:如何减少 CPU 负载?非常感谢!
史蒂芬
【问题讨论】:
-
使用
.animate()有什么问题?这是一个使用它的演示 - jsbin.com/oxode/2 你应该也可以使用animate淡入和淡出而没有问题 -
@Russ Cam:在一次运行(和其他事情)中增加和减少不透明度不要让我这样做。我希望我能……
-
如果它被拆分成对
animate的多个调用,这使得文本不断增长并且它在页面上的位置向下和向右移动,但还允许您进行调用以更改不透明度淡入淡出?
标签: javascript jquery text smoothing