代码之家  ›  专栏  ›  技术社区  ›  Shane Rowatt

HTML contenteditable在进入选项卡时工作,但在单击进入时不工作

  •  0
  • Shane Rowatt  · 技术社区  · 6 年前

    我想喝一杯 span 内容可编辑,所以我添加了 contentEditable ="true" 属性设置为span元素,但仅当我用键盘在字段中单击tab键时,该属性才可编辑,但如果我用鼠标光标单击文本,则该属性不可编辑。我认为可能有一些事件监听器在做一些古怪的事情,所以我做了一个恶意的黑客攻击来覆盖onclick和onfocus事件,使其不做任何事情,也不会传播到祖先事件监听器

    <span 
        onclick="javascript:return false;" 
        onfocus="javascript:return false;"  
        contentEditable ="true">Edit Me</span>
    

    作为一个例子,它不工作的标题 Gold Coast Waters 3 Day Forecast 应在以下页面上进行编辑: Non-Working Example

    下面的小提琴 contenteditable 所以我的代码中有一些东西阻止了它的工作,我似乎无法缩小它的范围。

    // find elements
    var banner = $("#banner-message")
    var button = $("button")
    
    // handle click and add class
    button.on("click", function(){
      banner.addClass("alt")
    })
    body {
      background: #20262E;
      padding: 20px;
      font-family: Helvetica;
    }
    
    #banner-message {
      background: #fff;
      border-radius: 4px;
      padding: 20px;
      font-size: 25px;
      text-align: center;
      transition: all 0.2s;
      margin: 0 auto;
      width: 300px;
    }
    
    button {
      background: #0084ff;
      border: none;
      border-radius: 5px;
      padding: 8px 14px;
      font-size: 15px;
      color: #fff;
    }
    
    #banner-message.alt {
      background: #0084ff;
      color: #fff;
      margin-top: 40px;
      width: 200px;
    }
    
    #banner-message.alt button {
      background: #fff;
      color: #000;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    
    <div id="banner-message">
      <span contenteditable="true">Hello World</span>
      <button>Change color</button>
    </div>

    当我点击 跨度 ?

    0 回复  |  直到 6 年前
        1
  •  0
  •   Shane Rowatt    6 年前

    结果是 $(".sortable").disableSelection() 有点恶心,会让元素停止 contenteditable="true" 使其不可编辑。我从代码中删除了这一行,元素现在可以编辑了。

    此外,jQuery不鼓励使用该函数: http://api.jqueryui.com/disableselection/