:hover sticks to element on drag and drop

随声附和 提交于 2019-12-09 14:51:23

问题


I have simple ol-li construction and want to add drag'n'drop to it. Additionaly I want to highlight hover item and dragover item in different colors. But it is an unusual bug in WebKit.

  1. Capture last item.
  2. Drag it to the top.
  3. Drop it to the first item.

And last element capture the hover pseudoclass! Why? How can I prevent it?

This is an example:

http://jsfiddle.net/zFk2V/3/

var lis = document.querySelectorAll("li"),
    ol = document.querySelector("ol"),
    dragged = false,
    dragover = false;
ol.addEventListener("drop", function(event) {
    ol.insertBefore(dragged,dragover);
    this.classList.remove("insistent");
}, false);
for (var i=0, n = lis.length; i < n; i++) {
    lis[i].addEventListener("dragstart", function(event) {
        dragged = this;
        ol.classList.add("insistent");
    }, false);
    lis[i].addEventListener("dragover", function(event) {
        if (dragover) {
            dragover.classList.remove("dragover");
        }
        event.preventDefault();
        dragover = this;
        this.classList.add("dragover");
    }, false);
}

回答1:


You can simply add an .onmouseover and an .onmouseout function and add/remove a class called hovered instead of using CSS's :hover. Here is the updated jsFiddle

Javascript to add (inside for loop)

lis[i].onmouseover = function() {
    // Adds the 'hovered' class
    this.className = this.className + " hovered";
}
lis[i].onmouseout = function() {
    // Removes the 'hovered' class
    this.className = this.className.split(' ').filter(function(v) {
        return v!='hovered'
    }).join(' ');
}

CSS

.hovered {
    background: #fc9;
}

Side note: I might add an id to the ol like id='dragableList' and change the line var lis = document.querySelectorAll("li") to var lis = document.getElementById('dragableList').querySelectorAll("li") just in case you have another list somewhere in your project later on. Here is the jsFiddle with that included




回答2:


Here is how I solved it. I had to resort to a little bit of JS unfortunately.

My page has collapsed records that highlight on hover. Clicking the record will expand it and disable the highlighting. Clicking again will re-collapse and resume hovering:

$(document).on('click', ".container.clickable", function(e){
  var $this = $(this);
  $this.toggleClass('expandable');
  if ($this.hasClass('expandable')) {
    $this.on('mouseenter', function(){
      // workaround to stop a stuck :hover
      $this.addClass('hilitable');
      $this.off('mouseenter');
    })
  } else {
    $this.removeClass('hilitable');
  }
});


来源:https://stackoverflow.com/questions/17946886/hover-sticks-to-element-on-drag-and-drop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!