我应该尽可能避免使用JS而是使用CSS吗? [英] Should I avoid JS when possible and use CSS instead?

查看:110
本文介绍了我应该尽可能避免使用JS而是使用CSS吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找最佳实践答案。目前我正在尝试将下拉菜单添加到我网站的导航栏中。我发现我可以使用CSS来完成它,我也可以使用JS - Angular来完成它。我已经读过,因为有了JS恶意的东西可以编程,有些人会禁用JS。因此,为了使您的网站功能在更多的计算机上,它应该用CSS编程。这有什么好处吗?我应该尽可能避免使用JS进行编码吗?

I'm looking for best practice answer. Currently I'm trying to add a dropdown menu to the navigation bar of my website. I've found that I could do it using CSS and that I could also do it using JS - Angular. I've read that because with JS malicious things can be programmed some people disable JS. Therefore to keep your websites functionality on more computers it should be programmed in CSS. Is there any merit to this? Should I avoid coding in JS when possible?

推荐答案

以下是几个重要的原因,为什么你更喜欢使用CSS而不是JS。

Here are few important reasons why you should prefer using CSS over JS.


  • 与JS
    动画相比,CSS动画的性能要好得多。 CSS没有像JS那样用于渲染动画的内存。

  • 如果你的动画取决于屏幕宽度,那么CSS媒体查询就像魅力一样没有任何延迟。但是如果必须使用JS实现这一点,则必须将事件绑定到窗口大小并对每个调整大小执行操作。

  • Javascript动画的开销总是略高于CSS动画因为最后JS动画会操纵动画的CSS样式。

然而,就像他们说的那样,每个优势都有其劣势。 CSS动画不能自由执行任何动画。

However, like how they say, every advantage has its disadvantage. CSS animations don't give the freedom to perform any animation.


动画元素的缩放,旋转和位置非常常见。在CSS中,它们都被塞入一个变换属性中,使得它们无法在单个元素上以真正独特的方式进行动画制作。例如,如果您想要独立地动画旋转和缩放,具有不同的时间和缓动,该怎么办?也许一个元素不断地发出脉冲(振动音阶)并且你想在翻滚时旋转它。这只适用于JavaScript。

Animating the scale, rotation, and position of an element is incredibly common. In CSS, they're all crammed into one "transform" property, making them impossible to animate in a truly distinct way on a single element. For example, what if you want to animate "rotation" and "scale" independently, with different timings and eases? Maybe an element is continuously pulsing (oscillating scale) and you'd like to rotate it on rollover. That's only possible with JavaScript.

参考: 神话喧嚣:CSS动画与JavaScript

如果你想要JS动画的灵活性和CSS动画的速度,你应该尝试 GSAP ,它建立在JavaScript之上,比CSS动画要快得多。 此处是表演测试比较CSS动画(使用 Zepto ), jQuery 动画和 GSAP 动画。不要忘记,结果可能会根据渲染引擎而有所不同。

If you want the flexibility of JS animations and the speed of CSS animations, you should try GSAP, which is built on JavaScript and is much faster than CSS animations. Here is the performance test comparing CSS animations (using Zepto), jQuery animations and GSAP animations. Not to forget, the results may vary as per the rendering engine.

结论:
这是你如何去做的。

Conclusion: This is how you can go about it.

简单的动画,CSS可实现:使用CSS

Simple animations, CSS achievable: Use CSS

简单的动画,用CSS无法实现:使用JS

Simple animations, can't achieve with CSS: Use JS

重型动画:使用 GSAP 或制作动画使用 requestAnimationFrame

Heavy animations: Use GSAP or craft your animations with requestAnimationFrame.

这里是CSS动画和JS requestAnimationFrame 实现之间惊人的性能比较。

Here is an amazing performance comparison between CSS animation and JS requestAnimationFrame implementations.

这篇关于我应该尽可能避免使用JS而是使用CSS吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆