2014 के डी-चयन मामलों के राज्य
मैंने खुद का कुछ शोध किया। यहां मैंने जो फ़ंक्शन लिखा है और इन दिनों का उपयोग कर रहा हूं:
(function deselect(){
var selection = ('getSelection' in window)
? window.getSelection()
: ('selection' in document)
? document.selection
: null;
if ('removeAllRanges' in selection) selection.removeAllRanges();
else if ('empty' in selection) selection.empty();
})();
मूल रूप से, getSelection().removeAllRanges()वर्तमान में सभी आधुनिक ब्राउज़रों (IE9 + सहित) द्वारा समर्थित है। यह स्पष्ट रूप से आगे बढ़ने की सही विधि है।
संगतता मुद्दों के लिए जिम्मेदार:
- क्रोम और सफारी के पुराने संस्करणों का इस्तेमाल किया
getSelection().empty()
- IE8 और नीचे इस्तेमाल किया
document.selection.empty()
अपडेट करें
संभवतः पुन: उपयोग के लिए इस चयन कार्यक्षमता को लपेटना एक अच्छा विचार है।
function ScSelection(){
var sel=this;
var selection = sel.selection =
'getSelection' in window
? window.getSelection()
: 'selection' in document
? document.selection
: null;
sel.deselect = function(){
if ('removeAllRanges' in selection) selection.removeAllRanges();
else if ('empty' in selection) selection.empty();
return sel; // chainable :)
};
sel.getParentElement = function(){
if ('anchorNode' in selection) return selection.anchorNode.parentElement;
else return selection.createRange().parentElement();
};
}
// use it
var sel = new ScSelection;
var $parentSection = $(sel.getParentElement()).closest('section');
sel.deselect();
मैंने इसे एक सामुदायिक विकी बना दिया है ताकि आप लोग इसमें कार्यक्षमता जोड़ सकें, या मानकों के विकसित होने पर चीजों को अपडेट कर सकें।
document.selectionइसका मतलब यह है कि इसका एकempty()तरीका है। आपने हर दूसरे मामले में विधि के लिए परीक्षण किया है, इसलिए आपemptyअंतिम मामले में भी परीक्षण कर सकते हैं।