How do I convert a CSS background-position property from percentages into pixels?

拈花ヽ惹草 提交于 2019-12-07 10:32:48

问题


I'm centering a background right now (using background-position: 50% 50%;), that I'd like to animate using Javascript. But, I want to be able to animate this using pixel measurements. Effectively I want to set the background-position to something like "50% + 10px". Is this possible using Javascript?

I can possibly do it by finding the height of the background image and the height of the browser screen and do some arithmetic, but this seems like a convoluted solution.


回答1:


In the future this will be possible using CSS3's calc function. But since that's not widely supported right now, below is a more practical solution.

Simply use the incremental notation jQuery supports for these properties. For example

$(some-element).css({ "background-position": "+=10px" });

This syntax was supported by $.animate before it was supported by $.css, but recent versions of jQuery support it in both cases.

Here's a jsfiddle demonstrating it in action.



来源:https://stackoverflow.com/questions/12044361/how-do-i-convert-a-css-background-position-property-from-percentages-into-pixels

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