本文介绍了在点击时切换contentEditable的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在单击时创建一个div contentEditable,然后在mouseout上将contentEditable设置为false,但到目前为止我还没有成功。点击一个链接会突出显示它,但除此之外什么都不做:

I'm trying to make a div contentEditable when it is clicked, and then set contentEditable to false on mouseout, but I've had no success so far. Clicking a link appears to highlight it, but otherwise does nothing at all:

<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>

我希望链接可以在点击链接时将我带到链接页面,但相反,它是点击时突出显示,并没有做任何事情。我怎样才能解决这个问题?

I expected the link to take me to the linked page when it was clicked, but instead, it was highlighted when clicked and did nothing else. How can I fix this problem?

推荐答案

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

Don't ever use inline html script declaration, thats a bad practice. I think the reason your link doesn't do anything is, that the event listener bubbled/propagated over it and changed its default onclick event, when you set it for your div.

我建议你做这样的事情。

I suggest you do something like this.

        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>

这篇关于在点击时切换contentEditable的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-20 02:13