单击时切换contentEditable

时间:2013-04-13 21:27:02

标签: javascript html contenteditable

我正在尝试在单击时创建div contentEditable,然后在mouseout上将contentEditable设置为false,但到目前为止我没有成功。单击链接似乎突出显示它,但完全不执行任何操作:

http://jsfiddle.net/GeVpe/19/

<div id="content" contentEditable="true" onclick = "this.contentEditable = true;" onmouseout = "this.contentEditable = false;">
    Surprisingly, <a href="http://google.com">clicking this link does nothing at all.</a> How can I fix this problem?
</div>

我希望链接能够在点击链接时将我带到链接页面,而是在点击时突出显示,并且不做任何其他操作。我该如何解决这个问题?

3 个答案:

答案 0 :(得分:3)

不要使用内联html脚本声明,这是一个不好的做法。我认为你的链接没有做任何事情的原因是,当你为你的div设置它时,事件监听器在它上面冒泡/传播并改变了它的默认onclick事件。

我建议你这样做。

        window.onload = function() {
            var div = document.getElementById('editable');
            div.onclick = function(e) {
                this.contentEditable = true;
                this.focus();
                this.style.backgroundColor = '#E0E0E0';
                this.style.border = '1px dotted black';
            }

            div.onmouseout = function() {
                this.style.backgroundColor = '#ffffff';
                this.style.border = '';
                this.contentEditable = false;
            }
        }

        // And for HTML

        <div id="content">
            <span id='editable'>Surprisingly,</span>
            <a href="http://google.com">clicking this link does nothing at all.</a>
        </div>

答案 1 :(得分:1)

 Here we can make html element editable true and false using this code. 

    $( "#mylabel" ).click(function() {
// we get current value of html element
        var value = $('#editablediv').attr('contenteditable');
//if its false then it make editable true
    if (value == 'false') {
        $('#editablediv').attr('contenteditable','true');
    }
    else {
//if its true then it make editable false
        $('#editablediv').attr('contenteditable','false');
    }
    });

答案 2 :(得分:0)

尝试将目标设置为blank

<div id="content" contentEditable="true" onclick = "this.contentEditable = true;" onmouseout = "this.contentEditable = false;">
    Surprisingly, <a href="http://google.com" target = "blank">clicking this link does nothing at all.</a> How can I fix this problem?
</div>