html - 如何在 div 上模拟 onblur 事件

标签 html

在代码示例中,同时单击两个 div 会使背景颜色变为灰色。

第二次单击第一个 div(内容可编辑)会将颜色变回白色。单击第二个 div(内容不可编辑)不会。

有没有办法轻松实现第二个 div 的相同结果?

<div contenteditable="true" style="width:100px; height:100px; border: 1px solid red;" onclick="this.style.backgroundColor='gray'" onblur="this.style.backgroundColor='white'"></div>

<div style="width:100px; height:100px; border: 1px solid blue;" onclick="this.style.backgroundColor='gray'" onblur="this.style.backgroundColor='white'"></div> 

https://jsfiddle.net/2u3e0d1v/

最佳答案

我不确定是否有一种方法可以精确地模拟 onblur...我会使用类似于这个的 jQuery 函数 here .

例如:

$(document).mouseup(function (e)
  {
      var container = $(".noteditable");
 
      if (!container.is(e.target) // if the target of the click isn't the container...
          && container.has(e.target).length === 0) // ... nor a descendant of the container
      {
          container.css('background-color', 'white');
      }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div contenteditable="true" style="width:100px; height:100px; border: 1px solid red;" onclick="this.style.backgroundColor='gray'" onblur="this.style.backgroundColor='white'"></div>

<div class="noteditable" style="width:100px; height:100px; border: 1px solid blue;" onclick="this.style.backgroundColor='gray'"></div>


或者在纯 JS 中类似这样的东西:

function resetBg(){
    if(window.event.srcElement.id != 'noteditable'){
        document.getElementById('noteditable').style.backgroundColor = 'white';
    }
}

document.onclick = resetBg;
<div contenteditable="true" style="width:100px; height:100px; border: 1px solid red;" onclick="this.style.backgroundColor='gray'" onblur="this.style.backgroundColor='white'"></div>

<div id="noteditable" style="width:100px; height:100px; border: 1px solid blue;" onclick="this.style.backgroundColor='gray'"></div>

关于html - 如何在 div 上模拟 onblur 事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28665696/

相关文章:

javascript - 如何保持焦点按钮和发送按钮焦点在表单上?

html - 如何创建具有绝对主体的绝对和相对页脚的导航栏

html - CSS:包含与水平规则对齐的 block 的多列布局

html - 如何使标题位于 Bootstrap 3 中的居中图片下方?

javascript - 根据用户指定的数字动态添加 HTML 表单字段

javascript - <div> 中的文本重叠

php - 关于这个的问题。来自 ."operation"

c# - 正则表达式提取属性值

html - 如何获取图片下方的文字?

html - 如何展开所有内联 block div 以填充父级?