Is there a CSS “:drop-hover” pseudo-class?

前端 未结 2 1035
眼角桃花
眼角桃花 2021-02-11 16:35

Saying I have an input type=\"file\" field. One can drop a file on this input(like in Firefox) instead of clicking \"browse\" and selecting the file.

相关标签:
2条回答
  • 2021-02-11 17:19

    UPDATE: Thanks to @Renato's comment, according to https://github.com/w3c/csswg-drafts/issues/2257, the drop pseudo-class has been dropped now.


    There is :drop and :drop() pseudo-class, which is currently in Working Draft status.

    According to http://css4.rocks/selectors-level-4/drag-and-drop-pseudo-class.php, the browser support is not good.

    For "file being dropped is not accepted" case, :drop(invalid active) is expected to work, in future.

    0 讨论(0)
  • 2021-02-11 17:21

    I had the same question and solved it a little differently than nashcheez. Still using JavaScript, though (I used jQuery here to simplify things):

    function drag(ev) {
      ev.dataTransfer.setData("text", "foo");
    }
    
    function allowDrop(ev) {
      $(ev.target).attr("drop-active", true);
      ev.preventDefault();
    }
    
    function leaveDropZone(ev) {
      $(ev.target).removeAttr("drop-active");
    }
    
    function drop(ev) {
      ev.preventDefault();
      $(ev.target).removeAttr("drop-active");
      alert(ev.dataTransfer.getData("text"));
    }
    #draggableItem {
      height: 50px;
      width: 150px;
      background-color: #eee;
    }
    
    #dropZone {
      height: 50px;
      width: 150px;
      background-color: #efe;
    }
    
    #dropZone[drop-active=true] {
      box-shadow: inset 0px 0px 0px 2px #00C;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    
    <div id="draggableItem" draggable="true" ondragstart="drag(event);">Drag Me</div>
    
    <div id="dropZone" ondragover="allowDrop(event);" ondragleave="leaveDropZone(event);" ondrop="drop(event);">Drop Here</div>

    I've tested this on Safari, Firefox and Chrome, but I haven't tried IE. I'm probably breaking a rule with the custom attribute, but it seems to work while I'm waiting for CSS4.

    0 讨论(0)
提交回复
热议问题