gpt4 book ai didi

javascript - 使用 CSS/JavaScript 安排动画?

转载 作者:太空宇宙 更新时间:2023-11-04 10:38:19 25 4
gpt4 key购买 nike

我们有一个 Web 应用程序需要以某种顺序在页面上显示来自服务器的消息。可以使用 JavaScript 一次下载所有消息,但它们应该只在预定时间显示。例如,如果有三个消息:

[
{ "content": "foo", "offset": 1 },
{ "content": "bar", "offset": 2 },
{ "content": "poi", "offset": 3 }
]

它们应该在页面加载后的 1 秒、2 秒和 3 秒出现在页面上,并且它们中的每一个都应该在以某种方式在页面上动画后从页面上消失(独立于其他)。

我的问题是:

  1. 是使用 JavaScript 动态地向页面添加/从页面删除消息元素,还是一次将所有消息添加到页面(首先隐藏)并使用 CSS 动画延迟更好?控制他们的外表?可能有很多消息(例如 10000 条)。

  2. 对于您认为合适的方式(CSS/JavaScript),您能否就如何实现给出一些建议?我是后端开发人员,所以我不太确定该怎么做。一些指导或想法表示赞赏。

最佳答案

每次有一个元素刷新内容肯定比 10000 个逐渐显示的隐藏元素更好。

在 JQuery 中,你可以这样做:

//when you get your messages from the server:

var messageQueue = [
{ "content": "foo", "offset": 1 },
{ "content": "bar", "offset": 2 },
{ "content": "poi", "offset": 3 }
]

//identify where you want to put the message, i.e. $('body'), or some div

var target = $(wherever you want to print the message)

//loop through the message queue giving each an offset

var delay = 1000; //this is 1s but you can make it anything you want
$.each(messageQueue, function(i, v) {
setTimeout(function() {
throwAcrossScreen(v.content);
}, v.offset * delay);
});

//create a temporary container for the message then fling it across the screen
//the element will be destroyed once it reaches the far side of the screen
//and the new message will appear at that moment

function throwAcrossScreen(message) {
var div = $('<div/>', {html: message})
.css({position: 'fixed', left: '0%'})
.appendTo(target)
.animate({left: '100%'}, 5000, function() {
div.remove()
});
};

这是一个jsfiddle在行动中展示它。

或者,用 CSS3 动画替换最后一部分:

function throwAcrossScreen(message) {
var div = $('<div/>', {html: message})
.addClass('message')
.appendTo(target)
.css({'left': '100%'});
setTimeout(function() {
div.remove()
}, 5000);
};

在你的 CSS 文件中有:

.message {
position: 'fixed';
left: '0%';
-webkit-transition: left 5s;
-moz-transition: left 5s;
-o-transition: left 5s;
-ms-transition: left 5s;
transition: left 5s;
}

虽然,this answer提出了一个更好的性能的替代方案。

关于javascript - 使用 CSS/JavaScript 安排动画?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36001824/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com