如何删除所选文本,目前是双击删除整个文本框

时间:2013-09-04 07:18:36

标签: javascript jquery html5

<!DOCTYPE html>
<html lang="en">

<head>
<meta charset=utf-8 />
<title>Basic Drag and Drop</title>
<style>
#drop {
  min-height: 200px;
  width: 200px;
  border: 3px dashed #ccc;
  margin: 10px;
  padding: 10px;
  clear: left;
}
p {
  margin: 10px 0;
}
#triangle {

  background: url(images/triangle.jpg) no-repeat;
}
#square {
  background: url(images/square.gif) no-repeat;
}
#circle {
  background: url(images/circle.jpg) no-repeat;
}
#red {
  background: url(images/red.jpg) no-repeat;
}
#yellow {
  background: url(images/yellow.jpg) no-repeat;
}
#green {
  background: url(images/green.jpg) no-repeat;
}
.drag {
  height: 48px;
  width: 48px;
  float: left;
  -khtml-user-drag: element;
  margin: 10px;
}
</style>
<script>
var addEvent = (function () {
  if (document.addEventListener) {
    return function (el, type, fn) {
      if (el && el.nodeName || el === window) {
        el.addEventListener(type, fn, false);
      } else if (el && el.length) {
        for (var i = 0; i < el.length; i++) {
          addEvent(el[i], type, fn);
        }
      }
    };
  } else {
    return function (el, type, fn) {
      if (el && el.nodeName || el === window) {
        el.attachEvent('on' + type, function () { return fn.call(el, window.event); });
      } else if (el && el.length) {
        for (var i = 0; i < el.length; i++) {
          addEvent(el[i], type, fn);
        }
      }
    };
  }
})();

(function () {

var pre = document.createElement('pre');
pre.id = "view-source"

// private scope to avoid conflicts with demos
addEvent(window, 'click', function (event) {
  if (event.target.hash == '#view-source') {
    // event.preventDefault();
    if (!document.getElementById('view-source')) {
      // pre.innerHTML = ('<!DOCTYPE html>\n<html>\n' + document.documentElement.innerHTML + '\n</html>').replace(/[<>]/g, function (m) { return {'<':'&lt;','>':'&gt;'}[m]});
      var xhr = new XMLHttpRequest();

      // original source - rather than rendered source
      xhr.onreadystatechange = function () {
        if (this.readyState == 4 && this.status == 200) {
          pre.innerHTML = this.responseText.replace(/[<>]/g, function (m) { return {'<':'&lt;','>':'&gt;'}[m]});
          prettyPrint();
        }
      };

      document.body.appendChild(pre);
      // really need to be sync? - I like to think so
      xhr.open("GET", window.location, true);
      xhr.send();
    }
    document.body.className = 'view-source';

    var sourceTimer = setInterval(function () {
      if (window.location.hash != '#view-source') {
        clearInterval(sourceTimer);
        document.body.className = '';
      }
    }, 200);
  }


});

})();
</script>

<style id="jsbin-css">

</style>
</head>
<body>
  <div class="drag" id="triangle" draggable="true"></div>
  <div class="drag" id="square" draggable="true"></div>
  <div class="drag" id="circle" draggable="true"></div>
  <div class="drag" id="red" draggable="true"></div>
  <div class="drag" id="yellow" draggable="true"></div>
  <div class="drag" id="green" draggable="true"></div>

  <div id="drop"></div>
<script>
function cancel(e) {
  if (e.preventDefault) {
    e.preventDefault();
  }
  return false;
}

var dragItems = document.querySelectorAll('[draggable=true]');

for (var i = 0; i < dragItems.length; i++) {
  addEvent(dragItems[i], 'dragstart', function (event) {
    // store the ID of the element, and collect it on the drop later on
    event.dataTransfer.setData('Text', this.id);




  });
}


var drop = document.querySelector('#drop');

// Tells the browser that we *can* drop on this target
addEvent(drop, 'dragover', cancel);
addEvent(drop, 'dragenter', cancel);
addEvent(drop, 'drop', function (e) {
  if (e.preventDefault) e.preventDefault(); // stops the browser from redirecting off to the text.
 this.innerHTML += '<p>' + e.dataTransfer.getData('Text') + '</p>';

  return false;
});
</script>
<script>
document.getElementById('drop').ondblclick = function(){
this.innerHTML="";//remove your text here
};
</script>
</body>
</html>

在下面的行中是删除整个名为drop name的框。但我想删除我刚才添加的所选文本。其他文本,我仍然希望它留在下拉框内。是否需要逐个代码才能将内部数据丢失或如何处理?请帮助我......非常感谢。

document.getElementById('drop').ondblclick = function(){
    this.innerHTML="";//remove your text here
    };

1 个答案:

答案 0 :(得分:0)

如果您要删除/操作所选文本,请查看Selection和Range对象API的MDN,但请记住,这些可能仍然是非标准API

这里有一个jFiddle示例,它会报告所选范围并删除所选文字:

document.getElementById("drop").ondblclick = function() {
    var sel = window.getSelection(),
        range = sel.getRangeAt(0),
        text = this.innerHTML,
        toRemove,
        editedText;
    //console.log("sel ", sel, " range ", range);

    toRemove = text.substring(range.startOffset,range.endOffset);
    editedText = text.slice(0, range.startOffset) + text.slice(range.endOffset);

    console.log("toRemove ", toRemove);
    console.log("editedText ", editedText);
}

请记住,双击文本区域的行为可能会有所不同 - 如果我在Chrome中双击文字,则只会选择一个单词。