演示拖拉效果代码兼容ie firefox chrome浏览器
在开发拖动效果时,有一个非常恼人的地方要处理时,就是拖动时,文本被选中蓝色一片,容易造成用户分心,有损用户体验。通常我们是用下面代码来清理selection:
window.getSelection().removeAllRanges(); |
}else if(document.selection){ |
document.selection.empty(); |
但这东西在谷歌浏览器中,快速拖动还是会出现蓝色(人家的渲染效率就是高),另外,每拖动一像素就清理一次,这频繁的调用对于一些旧式浏览器可不是好事。最近研究CSS3,发现user-select这个东西,终于搞定这问题了。
首先,我们要检测浏览器是否支持它,FF与webkit系浏览器是支持,IE9与opera11是不支持。
var getStyleName= (function(){ |
var prefixes = ['', '-ms-','-moz-', '-webkit-', '-khtml-', '-o-']; |
var reg_cap = /-([a-z])/g; |
function getStyleName(css, el) { |
el = el || document.documentElement; |
var style = el.style,test; |
for (var i=0, l=prefixes.length; i < l; i++) { |
test = (prefixes[i] + css).replace(reg_cap,function($0,$1){ |
alert(getStyleName("user-select")) |
对于不支持的浏览器,我们可以借助它们的一些私有属性与事件,如unselectable,onselectstart。当拖动时,我们把它们绑定在文档对象上就行了。
if(typeof userSelect === "string"){ |
return document.documentElement.style[userSelect] = "none"; |
document.unselectable = "on"; |
document.onselectstart = function(){ |
当拖动结束时,我们再让文档变回可选择模式,注意一些值的变化,都是很奇特的名字。
if(typeof userSelect === "string"){ |
return document.documentElement.style[userSelect] = "text"; |
document.unselectable = "off"; |
document.onselectstart = null; |
[站长教学网提示:Ctrl+A全选/可修改后代码再运行!]
(责任编辑:ken)