代码之家  ›  专栏  ›  技术社区  ›  kumarharsh

对DOM范围的功能检测支持(Modernizr)

  •  2
  • kumarharsh  · 技术社区  · 13 年前

    曾经有一个人写了一个脚本,可以让他“一键选择”跨度的内容。他的密码依赖于全能者 $ ,使用jQuery的 浏览器检测 。它就像一个符咒。

    然后在一个决定性的日子, jQuery 1.9(查询1.9) 被释放了 破坏了他的密码 ,和心脏。浏览器检测被降级为传奇,再也看不到了。于是,他寻找新的方法 现代化者 图书馆这很酷,很彻底,看起来正是他想要的。唉,事实并非如此。

    图书馆缺少 他想要的功能,以检测他的浏览器是否支持 DOM范围 对象他被这种奇怪的疏忽弄糊涂了。他肯定在某个地方遗漏了一些东西。

    你能帮他找到合适的工具来进行特征检测吗 DOM范围 ?

    3 回复  |  直到 13 年前
        1
  •  1
  •   Tim Down    13 年前

    只要发现你需要什么。以下确实做出了一些假设( document.createRange() window.getSelection() 暗示范围和选择方法的存在),但这是一个合理的折衷方案。

    演示: http://jsfiddle.net/dCvgU/

    代码:

    $("span").click(function() {
        var body = document.body, range, sel;
        if (typeof document.createRange != "undefined" &&
                typeof window.getSelection != "undefined") {
            range = document.createRange();
            range.selectNode(this);
            sel = window.getSelection();
            sel.removeAllRanges();
            sel.addRange(range);
        } else if (typeof body.createTextRange != "undefined") {
            range = body.createTextRange();
            range.moveToElementText(el);
            range.select();
        }
    });
    
        2
  •  1
  •   whitneyit    13 年前

    这个代码足够吗?

    var supportsRange = typeof Range === 'object' && typeof document.createRange === 'function' && typeof Selection === 'object' &&  typeof Selection.prototype.getRangeAt === 'function';
    
    if ( supportsRange ) {
        //
    }
    
        3
  •  0
  •   kumarharsh    13 年前

    为了完整起见,这里有两个答案的更完整版本,包装为jquery插件。 该插件支持所有主流浏览器。

    (它在coffescription中,对于js代码,请前往 js2coffee )

    $.fn.selectText = () ->
      @each ->
        text = this
        # FF, Chrome, IE9+, and hopefully Opera
        if document.createRange? and window.getSelection?
          selection = window.getSelection()
          range = document.createRange()
          range.selectNodeContents text
          selection.removeAllRanges()
          selection.addRange range
        # <= IE8
        else if document.body.createTextRange?
          range = document.body.createTextRange()
          range.moveToElementText text
          range.select()
        # Safari
        else if window.getSelection?
          selection = window.getSelection()
          selection.setBaseAndExtent text, 0, text, 1
    
    推荐文章