Force jQuery animations to use integer values

故事扮演 提交于 2019-12-06 05:19:08

问题


Is there a way (keeping forward-compatibility in mind) to force jQuery animations to use only integer values amidst an animation?

I'm animating an element's width.

<div style="width: 25px">...</div>

I look at the element in the inspector while it's in the middle of animating, and often the value has massive granularity decimalwise.

<div style="width: 34.24002943013px">...</div>

It only 'calms down' to integers once it's reached its goal.

<div style="width: 50px">...</div>

Usually I wouldn't bother myself about this as it's obviously functional.

However, in this project it's imperative that I stay pixel-perfect at all times, and I'm afraid using fractional pixel widths (or any other attribute measured in pixels) would render inconsistently between browsers. I know letter-spacing for one does.

Is there a way to make sure jQuery only uses decimal-free values even in the middle of animation?

EDIT: I feel like I should clarify; I'm not just using .animate({width:50}). Most of my animations are jQuery UI -powered .hide()s and .show()s, and the solution I'm looking for should obviously also work with those.


回答1:


For me this worked in the right way:

$("div").animate({ width: 50}, {
    duration: 1000,
    step: function(now, fx){
        fx.now = parseInt(now);
    }
});​



回答2:


Something like this?

$("div").animate({ width: 50}, {
  duration: 1000,
  step: function(now, fx){

      var value = parseInt($(this).css("width"));

     $(this).css("width", value);
  }
});​

This way, in each "frame" of the animation, the width value will be parsed into an integer value.

The animation will be less smoother this way, since you're cutting some values, but if your animation is long enough, it won't be even noticed.



来源:https://stackoverflow.com/questions/12078635/force-jquery-animations-to-use-integer-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!