Table of Contents
Insert and delete style sheet rules
Query all style sheet contents
Add and delete rules
insertRule() method
deleteRule() method
Create a new style sheet
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)

Aug 11, 2018 am 10:40 AM
css javascript

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!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to use bootstrap in vue How to use bootstrap in vue Apr 07, 2025 pm 11:33 PM

Using Bootstrap in Vue.js is divided into five steps: Install Bootstrap. Import Bootstrap in main.js. Use the Bootstrap component directly in the template. Optional: Custom style. Optional: Use plug-ins.

The Roles of HTML, CSS, and JavaScript: Core Responsibilities The Roles of HTML, CSS, and JavaScript: Core Responsibilities Apr 08, 2025 pm 07:05 PM

HTML defines the web structure, CSS is responsible for style and layout, and JavaScript gives dynamic interaction. The three perform their duties in web development and jointly build a colorful website.

Understanding HTML, CSS, and JavaScript: A Beginner's Guide Understanding HTML, CSS, and JavaScript: A Beginner's Guide Apr 12, 2025 am 12:02 AM

WebdevelopmentreliesonHTML,CSS,andJavaScript:1)HTMLstructurescontent,2)CSSstylesit,and3)JavaScriptaddsinteractivity,formingthebasisofmodernwebexperiences.

How to write split lines on bootstrap How to write split lines on bootstrap Apr 07, 2025 pm 03:12 PM

There are two ways to create a Bootstrap split line: using the tag, which creates a horizontal split line. Use the CSS border property to create custom style split lines.

How to set up the framework for bootstrap How to set up the framework for bootstrap Apr 07, 2025 pm 03:27 PM

To set up the Bootstrap framework, you need to follow these steps: 1. Reference the Bootstrap file via CDN; 2. Download and host the file on your own server; 3. Include the Bootstrap file in HTML; 4. Compile Sass/Less as needed; 5. Import a custom file (optional). Once setup is complete, you can use Bootstrap's grid systems, components, and styles to create responsive websites and applications.

How to insert pictures on bootstrap How to insert pictures on bootstrap Apr 07, 2025 pm 03:30 PM

There are several ways to insert images in Bootstrap: insert images directly, using the HTML img tag. With the Bootstrap image component, you can provide responsive images and more styles. Set the image size, use the img-fluid class to make the image adaptable. Set the border, using the img-bordered class. Set the rounded corners and use the img-rounded class. Set the shadow, use the shadow class. Resize and position the image, using CSS style. Using the background image, use the background-image CSS property.

How to use bootstrap button How to use bootstrap button Apr 07, 2025 pm 03:09 PM

How to use the Bootstrap button? Introduce Bootstrap CSS to create button elements and add Bootstrap button class to add button text

How to resize bootstrap How to resize bootstrap Apr 07, 2025 pm 03:18 PM

To adjust the size of elements in Bootstrap, you can use the dimension class, which includes: adjusting width: .col-, .w-, .mw-adjust height: .h-, .min-h-, .max-h-

See all articles