简体   繁体   English

在可信的元素上聚焦/模糊事件

[英]Focus / blur events on contenteditable elements

I'm trying to listen to focus / blur events on span with contenteditable=true attribute. 我正在尝试使用contenteditable=true属性来监听span上的焦点/模糊事件。

So here's what I tried (jQuery) : 所以这就是我尝试过的(jQuery):

$('.editable').on('focus',function(){
    var that = $(this),
        defaultTxt = that.data('default');
    that.html('');
});
$('.editable').on('blur',function(){
    var that = $(this),
        defaultTxt = that.data('default');
    if(that.html() === ''){
        that.html(defaultTxt);
    }
});

But he doesn't seem to work, because span doesn't handle focus / blur . 但他似乎没有工作,因为span不能处理焦点/模糊 How can I achieve that anyway (IE8 support needed) ? 我怎么能实现这一点(需要IE8支持)?

There are two ways to achieve this effect. 有两种方法可以达到这种效果。

Approach 1: focusin and focusout 方法1: focusinfocusout

$('.editable').on('focusin', function() {
    // your code here
});

$('.editable').on('focusout', function() {
    // your code here
});

focusin and focusout are like focus and blur events, but unlike the latter, they are fired on almost(?) every element, and also bubble. focusinfocusout就像focusblur事件一样,但与后者不同,它们几乎(?)每个元素都被触发,并且还会出现泡沫。 focusin and focusout are a part of DOM level 3 Specification. focusinfocusout是DOM 3级规范的一部分。 Firefox 51 and older didn't support this due to a known bug , but Firefox 52 and above have full support. 由于已知错误 ,Firefox 51及更早版本不支持此功能,但Firefox 52及更高版本完全支持。

Approach 2: click and focus 方法2: clickfocus

This only works if you have other focus able elements around your span. 这仅适用于您的跨度周围有其他可focus元素的情况。 What you do is basically use the focus event on any other element as a blur handler. 你所做的基本上是将focus事件用在任何其他元素上作为模糊处理程序。

$('.editable').on('click', function() {
    // your code here
});

$('*').on('focus', function() {
    // handle blur here
    // your code here
});

I wouldn't recommend this approach in a large webapp, because browser performance will take a hit. 我不建议在大型webapp中使用这种方法,因为浏览器性能会受到影响。

I have created a demo for you: 我为你创建了一个演示:

 $('.editable').bind('click', function(){ $(this).attr('contentEditable',true); }); $('.editable').bind('focus', function() { var that = $(this); //defaultTxt = that.data('default'); that.html(''); }); $('.editable').bind('blur', function() { var that = $(this); var defaultTxt = that.data('default'); if(that.html() === ''){ that.html(defaultTxt); } }); 
 .editable{ padding: 5px; border: 1px solid black; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script> <span class="editable" data-default="default">Some text</span> 

I have changed your code, take a look it. 我已经改变了你的代码,看看它。 Also now it's keeping the old value when lost the focus if you don't type anything. 此外,如果您不输入任何内容,它会在失去焦点时保留旧值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM