最初的mousedown事件发生后如何取消文本选择?
时间:2020-03-06 14:31:44 来源:igfitidea点击:
我正在尝试实现一个基于单击并按住的弹出菜单,将其定位为(真正)缓慢的点击仍会触发默认操作,并设置了延迟,以便不会出现文本选择手势通常会触发菜单。
我似乎无法做的是首先以一种不会阻止文本选择的方式取消文本选择:从事件处理程序中返回false(或者调用$(this).preventDefault()
)阻止了用户的选择,明显的$()。trigger('mouseup')
根本对选择没有任何作用。
- 这是在页面的一般上下文中,而不是特定于文本区域或者其他文本字段。
- e.stopPropogation()不会取消文本选择。
- 我不是要阻止文本选择,而是要在满足某些条件的情况下在短时间后否决它们。
解决方案
试试这个:
var input = document.getElementById('myInputField'); if (input) { input.onmousedown = function(e) { if (!e) e = window.event; e.cancelBubble = true; if (e.stopPropagation) e.stopPropagation(); } }
如果没有,请阅读以下内容:
http://www.quirksmode.org/js/introevents.html
$(this).focus()(或者类似于document.body.focus()的任何东西)似乎可以解决问题,尽管我在ff3以后没有做过很多测试。
我不确定这是否会帮助,但是下面是一些取消选择文本的代码:
// onselectstart is IE-only if ('undefined' !== typeof this.onselectstart) { this.onselectstart = function () { return false; }; } else { this.onmousedown = function () { return false; }; this.onclick = function () { return true; }; }
在这种情况下," this"将是我们要阻止其文本选择的元素。
除了顶级线程之外,还有一种正式的方法可以实现我想在DOM中实现的功能。可以用来代替事件的是称为范围对象。
考虑一下,(它绝对适用于FF3)
window.onclick = function(evt) { // retrieves the selection and displays its content var selectObj = window.getSelection(); alert(selectObj); // now collapse the selection to the initial point of the selection var rangeObj = selectObj.getRangeAt(0); rangeObj.collapse(true); }
不幸的是,这在IE,Opera,Chrome或者Safari上并不十分有效。不知道为什么,因为在Opera,Chrome或者Safari中,崩溃和getRangeAt方法都有关联。如果我知道更多,我会告诉你。
我上一个答案的更新(更通用)是选择对象和collapse,collapseToStart,collapseToEnd方法。 (链接文字)
现在考虑上面的2.0:
window.onmouseup = function(evt) { var selectObj = window.getSelection(); alert(selectObj); // to get a flavor of what you selected // works in FF3, Safari, Opera, and Chrome selectObj.collapseToStart(); // works in FF3, Safari, Chrome (but not opera) /* selectObj.collapse(document.body, 0); */ // and as the code is native, I have no idea why... // ...and it makes me sad }