【问题标题】:Change cursor while moving mouse移动鼠标时更改光标
【发布时间】:2017-07-14 05:00:45
【问题描述】:

我在移动/拖动鼠标时尝试在元素上放置“移动”类时遇到了一个奇怪的错误。我在 Chrome 59.0.3071.115 上使用 jQuery 3.1.1。

我已将问题简化为以下示例:

<html>
<head>
<style>
    .thing {
        display: block;
        width: 10em;
        height: 10em;
        background: green;
    }
    .moving {
        cursor: move;
    }
</style>
<script src="jquery-3.1.1.min.js"></script>
</head>
<body>
<div class="thing"></div>
<script>
    $(document).ready(function(){
        var $thing = $('.thing');
        $thing.on('mousedown', function(e){
            $thing.addClass("moving");
            console.log("mousedown");
        }).on('mouseup', function(e){
            $thing.removeClass("moving");
            console.log("mouseup");
        });
    });
</script>
</body>
</html>

这将在页面中显示一个绿色框,并在您按下鼠标和向上鼠标时触发事件。

会发生什么……

  1. 点击绿色框——“moving”类被应用到div(这可以在Chrome开发者工具:元素标签中看到),但是光标停留在通常的箭头上。我希望光标变为 move 光标。
  2. 在按住点击的同时,稍微拖动一下 -- 光标仍然是默认箭头。
  3. 在绿色 div 上释放单击 -- 光标会暂时切换到 move 光标,但如果完全移动鼠标,则会切换回默认箭头。

我尝试了https://stackoverflow.com/a/16172027/1766230 等解决方案,但都没有运气。我尝试了 CSS、各种元素等中选择器的各种组合。奇怪的是,在 jsfiddle 中尝试此操作时一切正常,但是将此内容作为独立的 HTML 文件,我看到了错误。

编辑

原来它一定是浏览器错误,因为当我关闭 Chrome 并重新打开它时,它开始按预期工作。有人知道 Chrome 中的这种错误吗?

【问题讨论】:

  • 用你的例子对我来说很好。你得到什么错误?
  • 没有错误。描述中的编号列表中解释了这种奇怪的行为。
  • 对我来说工作得很好,你能做一件事就是将你的 jquery (jQuery 3.1.1) 替换为 code.jquery.com/jquery-3.2.1.min.js。可能与 jquery 端的一些版本控制问题有关。

标签: javascript jquery css google-chrome


【解决方案1】:

只是另一种选择(没有 JS)

  • 使用tabindex
  • 选择器是:active:hover

.thing {
  display: block;
  width: 10em;
  height: 10em;
  background: green;
  user-select: none;
  outline: none;
}

.thing:active:hover {
  cursor: move;
  background: red;
}
&lt;div class="thing" tabindex="1"&gt;&lt;/div&gt;

【讨论】:

    【解决方案2】:
    drag != mousedown
    

    它是浏览器默认的拖动行为。使用mousedown添加drag事件

    $(document).ready(function() {
      var $thing = $('.thing');
      $thing.on('mousedown ,drag', function(e) {
        $thing.addClass("moving");
        console.log("mousedown");
      }).on('mouseup', function(e) {
        $thing.removeClass("moving");
        console.log("mouseup");
      });
    });
    .thing {
      display: block;
      width: 10em;
      height: 10em;
      background: green;
    }
    
    .moving {
      cursor: move;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
    <div class="thing"></div>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-09-24
      • 1970-01-01
      • 2013-01-30
      • 2020-08-13
      • 1970-01-01
      • 2010-11-16
      • 2023-03-19
      • 2018-12-01
      相关资源
      最近更新 更多