Home > Web Front-end > JS Tutorial > How to write css animation in js? How to write css animation in js (code)

How to write css animation in js? How to write css animation in js (code)

不言
Release: 2018-08-11 10:40:12
Original
2902 people have browsed it

The content of this article is about how to write CSS animation in JS? The method (code) of writing CSS animation in JS has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Use setTimeout() or setInterval() to call a piece of code regularly using these two functions. This is the principle.

Purpose, repeatedly modify the inline style to achieve the effect of animation

By constructing the content of a frame in the same time, and then letting it continuously change the css under the action of the function value to achieve the effect of animation

JS writing css animation

// 将e转化为相对定位的元素,使得其可以左右移动
// 第一个参数为元素对象或者元素的id
// 如果第二个参数是函数,以e为参数,它将在动画结束时调用
// 第三个参数指定e移动的距离,默认为5像素
// 第四个参数指定移动多久,默认500毫秒
function shake(e, oncomplete, distance, time) {
    // 句柄函数
    if (typeof e === "string") e = document.getElemnentById(e);    // 如果传入的是对象的id则获取对象的id,如果传入的为元素(元素为对象)则直接跳过这一句
    if (!time) time = 500;    // 如果time是空值,则直接使用默认值
    if (!distance) distance = 5;    // 如果未指定移动的距离,则默认为5像素

    var originalStyle = e.style.cssText;    // 获取元素e的css样式
    e.style.position = "relative";    // 设置为相对定位
    var start = (new Date()).getTime();    // 设置动画开始的时间,获取一个格林威治时间
    animate();    // 动画开始

    // 函数检查消耗时间,并更新e的位置
    // 如果动画完成,它将e还原为原始状态
    // 否则,将会更新e的位置,安排其自身重新运行
    function animate() {
        var now = (new Date()).getTime();    // 获取现在的时间
        var elapsed = now-start;    // 从开始以来消耗了多长时间
        var fraction = elapsed / time;    // 为总时间的几分之几

        if (fraction < 1) {    // 如果动画未完成
            // 作为动画完成比例的函数,计算e的x位置
            // 使用正弦函数将完成比例乘以4pi
            // 所以,它将来回往返两次
            var x = distance * Math.sin(fraction * 4 * Math.PI);     // 使用正弦函数实现每秒四帧
            e.style.left = x + "px";

            // 在25毫秒后或在总时间的最后尝试再次运行函数
            // 目的是为了产生每秒40帧动画
            setTimeout(animate, Math.min(25, time-elapsed));    // 使用天花板函数再次调用,再次移动
        }
        else {    // 否则动画完成
            e.style.cssText = originalStyle; // 恢复原始样式
            if (oncomplete) oncomplete(e);    // 产生一个回调函数
        }
    }
}

// 以毫秒级的时间将e从完全不透明淡出到完全透明
// 在调用函数时假设e是完全不透明的
// oncomplete 是一个可选函数,以e为参数,它将在动画结束的时调用
// 如果不指定time,默认为500毫秒
function fadeOut(e, oncomplete, time) {
    if (typeof e === "string") e = document.getElementById(e);
    if (!time) time = 500;

    // 使用Math.sqrt作为一个缓动函数创建动画
    // 非线性函数,一开始淡出的较快,然后逐步的缓慢
    var ease = Math.sqrt;

    var start = (new Date()).getTime();    // 动画开始的时间
    animate();    // 动画开始

    function animate() {
        var elapsed = (new Date()).getTime()-start;    // 消耗的时间
        var fraction = elapsed/time;    // 总时间的几分之几

        if (fraction < 1) {    // 如果动画未完成
            var opacity = 1 - ease(fraction);    // 计算不透明度  即 完成一次变换,开方
            e.style.opacity = String(opacity);    // 设置透明度
            setTimeout(animate, // 进行下一帧
                Math.min(25, time-elapsed));    // 在25毫秒之后或者在总时间的最后再次调用
        }else {
            e.style.opacity = "0";    // 使得e完全透明
            if (oncomplete) oncomplete(e);    // 在结束的时候回调
        }
    }
}
Copy after login

Query the calculated style

getComputedStyle(e)
Copy after login

275 styles. . . O__O "…

Scriptable css classes

In addition to scripting inline styles, you can also script css classes

Remove and add classes

e.className = "attention";  // 添加类
e.className = "";   // 移除类
Copy after login

Display class list

classList
Read-only attribute, returns a real-time collection of element class attributes.

e.classList()
Copy after login

Scripted style sheet

Turn on and off styles Table

The CSSStyleSheet object of the style and link elements defines a disabled attribute that can be set and queried in js.

Regarding the disabled attribute, this attribute is not part of the specification in HTML and is not part of the specification in HTML. Exists, however, the attribute exists in the DOM. This attribute cannot be set in a tag, but it can be set in a script

If the value is true, the style sheet is closed, otherwise the style sheet is opened

e.disabled = true;
Copy after login

In this way, the style sheet can be closed.

Similarly, it can also be queried through the following methods

document.styleSheets[0].disabled;
Copy after login

Insert and delete style sheet rules

The CSSStyleSheet object is also defined for querying , api for inserting and deleting style sheet rules

Query all style sheet contents

var firstRule = document.styleSheets[0].cssRules[0];
Copy after login

document.styleSheets[0] A read-only property that returns a link to the document or an embedded style sheet

This style is read-only and cannot be inserted or deleted

selectorText is the css selector
cssText is the css text style

Add and delete rules

insertRule() and deleteRule() are two methods to add and delete rules
There is also an addRule() method

insertRule() method

insertRule() and deleteRule () These two methods are used to add and delete rules

ss.insertRule(".name {color:blue}", 0);
Copy after login

In the ss style sheet, add a css rule in the 0th cssRules. Make the font of the class name blue
If added If the index already exists, it will not be overwritten. All indexes will be incremented by 1, and then inserted

deleteRule() method

Delete style rule
Delete the last inserted style

ss.deleteRule(0);
Copy after login

Delete the 0th rule, and the style will continue to start from 0

Create a new style sheet

This is not difficult, directly insert a new style element and insert it into the new style through innerHTML css content, or directly insert the link tag, set and add an html attribute using the Element.setAttritube() method, set the rel value to the stylesheet, and then add the src attribute in the same way

Pure The operation of dom and bom does not involve any style sheet content

Related recommendations:

Which is faster, CSS or JS animation_html/css_WEB-ITnose

After the css animation ends, js cannot modify the translated value._html/css_WEB-ITnose

The above is the detailed content of How to write css animation in js? How to write css animation in js (code). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template