首页 > 解决方案 > 为什么 css 样式会这样?

问题描述

我基于 Pluralsight 上的“Scott Allen 的 RxJS 反应式编程入门”使用 angular-cli 创建了小型应用程序。它从鼠标创建 Observable 事件流。没什么特别的——数据流很好用。唯一的问题是样式对我来说以一种奇怪的方式应用。他们以未知的方式仅更新 div 2 次。当我在圆形区域中移动鼠标时,它们更改为 0px - 一次用于 x,一次用于 y 轴。一次,就是这样。我在开发人员工具中手动更改了这些属性,它的工作方式应该如此。但不能自动影响这种行为。

这是截图

html

#circle {
    width: 50px;
    height: 50px;
    border-radius: 50%;
    background-color: red;
    position: absolute;
}

<div id="circle"></div>

打字稿

ngOnInit() {
  let circle = document.getElementById('circle')
  let mouse = fromEvent(document, 'mousemove')
    .pipe(
      map((e: MouseEvent) => {
        return {
          x: e.clientX,
          y: e.clientY
        }
      }),
    )

  function onNext(value) {
    circle.style.left = value.x
    circle.style.top = value.y
    console.log("xy", value.x, value.y)
  }

  mouse.subscribe(
    value => onNext(value),
    e => console.log(`error: ${e}`),
    () => console.log('complete.')
  )

}

标签: htmlcssangular

解决方案


将“px”添加到值:

function onNext(value) {
        console.log(circle.style.left)
        circle.style.left = value.x + 'px'
        circle.style.top = value.y + 'px'
        console.log("xy", value.x, value.y)
      }

和圆圈将通过鼠标改变位置。演示


推荐阅读