javascript - 在 Safari Mobile 上以编程方式选择 DOM 元素(就像使用鼠标一样)?

标签 javascript select

希望以编程方式在 DOM 元素中选择 HTML,就像用户使用鼠标进行选择一样,正是为了避免让他们使用鼠标进行选择。

SO 帖子 ( Select all DIV text with single mouse click ) 中的这段优雅代码在我测试的笔记本电脑浏览器(IE、Chrome、FF、Windows 和 Mac 上的 Safari)上运行良好:

    function selectText(el) {
        if (document.selection) {
            var range = document.body.createTextRange();
                range.moveToElementText(el);
            range.select();
            console.log("select 1");
        } else if (window.getSelection) {
            var range = document.createRange();
            range.selectNode(el);
            window.getSelection().addRange(range);
                        console.log("select 2");
        }
        else {
          console.log("select 3");
        }
    };

JSFiddle: http://jsfiddle.net/z4yMh/7/

但不适用于 Safari 移动版(参见 JSFiddle)。移动开发控制台显示他的控制台显示 select 2 表示正在调用点击事件,移动开发控制台没有显示错误(即方法 selectNode() 似乎没有为 null),什么也没有发生。

猜不出为什么。谷歌搜索很难,因为 select 也用于指代不同概念的 jQuery/DOM 选择器。

我希望的是一种类似于 Safari 移动版中的原生选择的效果,如下图所示:

enter image description here

这个项目没有使用 jQuery,但如果能解决问题,jQuery 就可以了。

最佳答案

根据CSS Ninja

When setting a range iOS Safari won’t actually show the selection as highlighted but if you were to check the document selection it would return the correct content, desktop browsers will show the range selected in the document.

However if you do the same with a user action like tapping the “set selection range” button in the demo the iOS highlight will show up. Another interesting quirk is if I tap the content and bring the keyboard up but don’t dismiss it then refresh the page the programmatically set selection will show the iOS selection highlight.

Another interesting find is if you perform execCommand, which I’ll touch on later in the article, like bold it will apply the command to the selection made and make the iOS selection UI appear.

希望这对您有所帮助。

关于javascript - 在 Safari Mobile 上以编程方式选择 DOM 元素(就像使用鼠标一样)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20462424/

相关文章:

javascript - 使用 Selenium 或 HTMLUNIT 的 HttpClient?

javascript - 如何根据用户选择的 HTML 选项更改选择的背景颜色?

php - 如何进行多重选择来创建新行?

javascript - 如何在 CSS 中使用 macOS 系统强调色?

javascript - 如何测试一个值是字符串还是整数?

javascript - 如何从 JS 代码中排除某些 HTML 类

php - 从数据库中选择一个值

excel vba选择列

mysql - 检索对象中组合投票数最高的集合

javascript - 字符串中每次出现都执行一个函数