单击HTML后如何保持选择? [英] How to maintain selection after click in HTML?

查看:79
本文介绍了单击HTML后如何保持选择?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写WYSIWYG编辑器(不能使用像TinyMCE这样的东西 - 必须自己编写代码),我希望用户能够通过在HTML中添加标签将文本设置为粗体,下划线,链接等。我遇到的问题是,当用户选择可编辑div中的文本然后单击粗体按钮时,它无法找到选择,因为已经取消选择该选择,因为发生了单击事件。我怎么能阻止这个?有更好的方法吗?

I am coding a WYSIWYG editor (can't use something like TinyMCE - have to code myself) and I want users to be able to set the text as bold, underlined, links, etc by adding in tags to the HTML. The problem I've got is that when users select the text in the editable div and then click the 'Bold' button it is unable to find the selection because it has been deselected because the click event has happened. How can I stop this? Is there a better way to do this?

推荐答案

此功能可以帮助您:

jQuery.fn.getSelectedText = function() {
    var sSelectedText = "";
    // all browsers, except IE before version 9
    if (window.getSelection) {
        var sTagName = this.get(0).tagName.toLowerCase();
        sSelectedText = (
            sTagName == 'input' || sTagName == 'textarea' ?
            this.val().substring (
                this.get(0).selectionStart
                , this.get(0).selectionEnd
            ) :
            document.getSelection().toString()
        );
    }
    // Internet Explorer before version 9
    else {
        if (document.selection.createRange) {
            sSelectedText = document.selection.createRange().text;
        }
    }
    return sSelectedText;
}

另见 jsfiddle

=== UPDATE ===

=== UPDATE ===

如果您的按钮不是< input type =button / submit... /> <按钮...> ,您必须在每次点击后记住所选文字:

If your button isn't an <input type="button/submit" ... /> or a <button ...>, you have to remember the selected text after each click:

var sSelectedText = '';
$('body').click(function() {
    sSelectedText = $('#text').getSelectedText();
});
$('body').dblclick(function() {
    sSelectedText = $('#text').getSelectedText();
});

点击按钮,点击所选文字为sSelectedText:

On button click the selected text is in sSelectedText:

$('#button').click(function(e) {
    alert(sSelectedText);
});

另见我的新 jsfiddle

这篇关于单击HTML后如何保持选择?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆