我的脚本用似乎没有理由的东西改变了一些值

Gus*_*Wal 5 javascript

所以我一直在研究一个在鼠标坐标处产生气泡的脚本.这是一个非常基本的脚本,可以计算一些随机不透明度,随机大小等等.

var transform = (function () { // This piece is to test whether transform should be prefixed or not
  var testEl = document.createElement('div')
  if (testEl.style.transform == null) {
    var vendors = ['Webkit', 'Moz', 'ms']
    for (var vendor in vendors) {
      if (testEl.style[ vendors[vendor] + 'Transform' ] !== undefined) {
        return vendors[vendor] + 'Transform'
      }
    }
  }
  return 'transform'
})()

var bubbles = {}
bubbles.chance = 0.08  // Chance for a bubble to spawn at mousemove
bubbles.delay = 50     // Should minimally be 10, otherwise the circles can't transition from small to big
bubbles.duration = 800
bubbles.minScale = 0.2 // The scale of the bubbles will be anywhere between 0.2 and 1 of the default size defined by the CSS
bubbles.minOpacity = 0.4
bubbles.maxOpacity = 0.7

document.getElementById('bubbles').addEventListener('mousemove', function (e) {
  if (Math.random() < bubbles.chance) {
    var $el = document.createElement('div')
    var size = Math.random() * (1 - bubbles.minScale) + bubbles.minScale
    var transition = Math.round(bubbles.duration * 0.9)

    $el.style.transition = transition + 'ms ease-in-out'
    $el.style.top = e.offsetY + 'px'  // Seems to undergo a modulo for some periods of time
    $el.style.left = e.offsetX + 'px' // This one too
    $el.style[transform] = 'translate(-50%, -50%) scale(0)'
    $el.style.opacity = Math.random() * (bubbles.maxOpacity - bubbles.minOpacity) + bubbles.minOpacity

    window.setTimeout(function () {
      $el.style[transform] = 'translate(-50%, -50%) scale(' + size + ')'
      window.setTimeout(function () {
        $el.style[transform] = 'translate(-50%, -50%) scale(0)'
        window.setTimeout(function () {
          $el.parentNode.removeChild($el)
        }, transition)
      }, transition + bubbles.duration)
    }, bubbles.delay)

    document.getElementById('bubbles').appendChild($el)
  }
})
Run Code Online (Sandbox Code Playgroud)
html, body{height:100%}body{margin:0;background-color:#17C}

#bubbles{
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  overflow: hidden;
}

#bubbles > div{
  position: absolute;
  width: 12vw;
  height: 12vw;
  border-radius: 50%;
  background-color: #FFF;
}
Run Code Online (Sandbox Code Playgroud)
<div id="bubbles"></div>
Run Code Online (Sandbox Code Playgroud)

现在,由于某种原因,一些气泡没有放在正确的坐标上.该脚本应该逐字逐渐地产生e.offsetX并且e.offsetY每次它产生一个新的泡泡,但它有时似乎对值应用模数.

我认为应用某种模数的原因是因为当你只在水平线上移动时,所有移位的气泡也会形成一条水平线.纵向也是如此.

该脚本是vanilla JavaScript,错误似乎发生的部分在这里:

$el.style.top = e.offsetY + 'px'
$el.style.left = e.offsetX + 'px'
Run Code Online (Sandbox Code Playgroud)

值得注意的一个奇怪的事情是,位移不仅仅发生在一次一个气泡,而是发生在短时间内的所有气泡.

该错误发生在所有主流浏览器中.

所有输入都表示赞赏!

Jos*_*kle 7

我明白为什么会这样.如果您碰巧悬停在气泡而不是蓝色背景上,它会使用气泡作为offsetX和Y的参考.如果它是一个完整的应用页面,您可以使用e.clientXe.clientY不是.否则,如果事件被触发,您只需要监听事件#bubbles.

  • 将'pointer-events:none;`添加到气泡中就可以了! (2认同)