在代码示例中,同时单击两个 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>
最佳答案
我不确定是否有一种方法可以精确地模拟 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/