---
title: "firefox中iframe焦点丢失问题"
author: "yiminghe"
date: "2010-08-11T00:33:34Z"
tags: ["Firefox"]
categories: ["Web前端"]
slug: "firefox-iframe"
draft: false
lastmod: "2010-08-11T09:45:21Z"
id: 734137
url: "https://yiminghe.iteye.com/blog/734137"
---

**场景与问题：**

查看 demo：[ff-iframe-bug](http://lite-ext.googlecode.com/svn/trunk/lite-ext/playground/ff-ifame-focus/iframe-focus-bug.html)

初始状态下 iframe 中的内容可编辑，可选中，当动态改变 iframe 的 position（即改变 layout ）后，该 iframe 出现三个问题：

1\. 不可编辑

2\. 光标消失

3.原先选中区域（光标位置）丢失

**分析与修复：**

想不到一向稳重的 firefox 也会有这么折磨人的 bug，还好 ckeditor 已有完美解决方案，从纷繁芜杂的代码丛中理出来就是：

1.不可编辑，就重新设一遍 contentEditable

2.光标消失就绕一下：先由其它可获得焦点的元素获得焦点，然后 iframe 窗体以及 body 再获得焦点，最后惊奇发现光标回来了！不过到了编辑区最后 ....

3.丢失就要多保存：操作前保存选中区域以及光标位置(range)，操作后再把保存的 range 设置回去。

查看demo：[ff-iframe-fix](http://lite-ext.googlecode.com/svn/trunk/lite-ext/playground/ff-ifame-focus/iframe-focus-fix.html?v=2)

**代码实例：**

 

```
var savedRange = null;

//保存选择区域以及光标位置
function save() {
    var sel = win.getSelection();
    if (sel) {
        savedRange = sel.getRangeAt(0);
    }
}

function show() {

    if (UA.gecko) {
        //激活编辑与光标
        body.contentEditable = false;
        body.contentEditable = true;
        a[0].focus();
        win.focus();
        body.focus();

        //范围回复
        var sel = win.getSelection();
        sel.removeAllRanges();
        sel.addRange(savedRange);
    }

}
```