javascript - javascript 样式仅在使用 setTimeout 时应用于元素
问题描述
我在下面的片段和jsfiddle.net上有一个可行的解决方案
但是我不喜欢它,因为它仅在使用 setTimeout 且间隔值等于零或加号时才有效。
它应该可以在不必使用 setTimeout 的情况下工作,这与将间隔设置为零的逻辑相同。
有谁知道为什么没有 setTimeout 就不能工作?
const PACE = 4;
const CONTAINER = document.getElementById('container');
const ANCHOR = document.getElementById('anchor');
const ENTRIES = [{
'url': '#1',
'text': 'news nº 1'
},
{
'url': '#2',
'text': 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua'
},
{
'url': '#3',
'text': 'news nº 3'
},
{
'url': '#4',
'text': 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua'
}
];
let counter = 0;
function getDuration() {
return ((ANCHOR.getBoundingClientRect().width + CONTAINER.getBoundingClientRect().width) / CONTAINER.getBoundingClientRect().width) * PACE;
}
function moveAnchor() {
setTimeout(function() {
ANCHOR.style.transitionDuration = getDuration() + 's';
ANCHOR.style.left = (-1 * ANCHOR.getBoundingClientRect().width) + 'px';
}, 0);
// I want to replace the above code with:
//ANCHOR.style.transitionDuration = getDuration() + 's';
//ANCHOR.style.left = (-1 * ANCHOR.getBoundingClientRect().width) + 'px';
}
ANCHOR.addEventListener('transitionend', function() {
counter++;
if (counter === ENTRIES.length) {
counter = 0;
}
ANCHOR.href = ENTRIES[counter].url;
ANCHOR.innerHTML = ENTRIES[counter].text;
ANCHOR.style.transitionDuration = '0s';
ANCHOR.style.left = CONTAINER.getBoundingClientRect().width + 'px';
moveAnchor()
});
moveAnchor();
body {
margin: 0;
padding: 0;
}
#container {
position: fixed;
top: 0;
left: 0;
right: 0;
height: 50px;
background: firebrick;
overflow: hidden;
}
#anchor {
height: 100%;
display: flex;
align-items: center;
color: white;
position: absolute;
left: 100%;
transition-property: left;
transition-timing-function: linear;
white-space: nowrap;
}
<div id="container">
<a id="anchor" href="#1" target="_blank">news nº 1</a>
</div>
解决方案
推荐阅读
- ansible - ECS 集群的 Ansible 服务发现
- react-native - @react-native-community/NetInfo: Error when I tried to remove event listener
- python - “Dash plotly”:我在将两个输入连接到输出时遇到问题,而且 bas x 轴也没有排序和正确分类
- ruby - 使用 rspec 测试 ruby 脚本很热门
- firebase - 检索数据时出现异常:- 未布置 RenderBox
- google-apps-script - 为什么“category:social”在 GMail UI 搜索中使用,但在 GmailApp.search("category:social", 0, 500) 中不起作用
- python - 用不稳定的时间序列模型拟合时间序列
- flutter - 如何在snackbar中实现撤消功能,以便在flutter中的sqlite中进行硬删除和软删除?
- node.js - 错误:不能在模块外使用导入语句
- php - php文件不显示任何输出