【问题标题】:Change position through DOM EVENT FLOW - Jquery/JS通过 DOM 事件流改变位置 - Jquery/JS
【发布时间】:2020-03-28 13:35:00
【问题描述】:

我想在用户停止拖动<div> 后更改它的位置。没有逗号的数字10 也不起作用。

它确实会变成蓝色,但位置不会。我能做些什么? 我有很多.screen div。谢谢!

$('.screen').draggable({
  stop: function(event, ui) {
    if (parseInt(event.target.offsetTop) < -1) {
      event.target.style.backgroundColor = "blue";
      event.target.style.offsetTop = "10";
    }
  }
})

【问题讨论】:

  • 你试过 event.target.offsetTop = "10"
  • @RoryMcCrossan 你确定吗?我试过了,它不起作用。同样在 dom 中,它的编写没有任何单位。
  • @BerkÖztürk 不起作用。这样你就失去了属性的正确路径。
  • offsetTop 不是style 对象的属性,它直接在元素上,例如event.target.offsetTop = 10
  • @Yopi offsetTop 不是样式属性。你想做 event.target.style.top = "10px"?

标签: javascript jquery events dom-events target


【解决方案1】:

这里有两个主要问题。首先offsetTop是Element对象的一个​​属性,而不是Element的style

其次offsetTop只读,所以你不能用它来更新元素的位置。为此,您需要设置style.top:

$('.screen').draggable({
  stop: function(event, ui) {
    if (event.target.offsetTop < -1) {
      event.target.style.backgroundColor = "blue";
      event.target.style.top = '10px';
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>
<link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" />
<div class="screen">Drag me</div>

还要注意offsetTop 返回一个整数值,所以parseInt() 不是必需的。

【讨论】:

  • 非常感谢!!!!!!!!!!!!!它工作得很好。只是未来的问题:如何知道我只能阅读什么以及我可以改变什么。网上有名单吗?
  • 是的,请参考MDN。在这种情况下,如果您查看 offsetTop 的文档,您会看到它声明它是只读的
猜你喜欢
  • 2013-09-15
  • 2021-09-29
  • 2018-12-24
  • 2011-07-08
  • 1970-01-01
  • 2012-03-23
  • 2013-06-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多