首页 > 解决方案 > 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>

标签: javascriptcsscss-transitionssettimeout

解决方案


推荐阅读