首先说一下大致思路:wangEditor、mavon-editor聚焦时,需要给边框加样式,那么怎样才能知道目前是否是聚焦状态呢?
这时候就需要了解两个东西:document.activeElement、document.hasFocus
JavaScript中可以使用document.activeElement判断某一元素是否获取焦点。或使用hasFocus()方法检测文档内任一元素是否获取焦点。
document.activeElement
document.activeElement获取当前获得焦点的元素,在chrome总是得到body,后来经过测试得到结果如下:
IE:document.activeElement可获得所有聚焦的元素,包括input、textarea、div等。IE只关心光标聚焦的位置,不关心聚焦元素的性质。
- chrome:document.activeElement仅对input、textarea等标准的输入文本有效;对于div等非编辑类的元素(即使开启了contentEditable),返回的值为BODY。
- fireFox:document.activeElement可获得所有聚焦的元素。包括input、textarea、div等。
JavaScript判断一个文本框是否获得焦点
// 可以用document.activeElement判断
// document.activeElement表示当前活动的元素
// 查找你要判断的文本框
var myInput = document.getElementById('myInput');
if (myInput == document.activeElement) {
alert('获取焦点');
} else {
alert('未获取焦点');
}
activeElement :activeElement 属性返回文档中当前获得焦点的元素。
document.hasFocus
使用hasFocus()方法判断是否获取焦点
var x = document.getElementById("demo");
if (document.hasFocus()) {
x.innerHTML = "文档已获取焦点。";
} else {
x.innerHTML = "文档失去焦点。";
}
hasFocus():hasFocus() 方法返回布尔值,用于检测文档(或文档内的任一元素)是否获取焦点。
应用场景:
我们需要实现的是聚焦时,给边框变为蓝色框框,失焦时颜色变为之前默认的灰色框框
聚焦时
失焦时
css代码
.hasFocus{
.mw-editor-box{
.w-editor-box{
.w-e-toolbar{
border-top-color #4285F4 !important
border-bottom-color #fff !important
border-left-color #4285F4 !important
border-right-color #4285F4 !important
}
.w-e-text-container{
border-top-color #DCDFE6 !important
border-bottom-color #4285F4!important
border-left-color #4285F4 !important
border-right-color #4285F4 !important
}
}
}
.mavonEditor{
border 1px solid #4285F4
}
}
html代码
<div class="wikiStyle h260" :class="{'hasFocus' : hasFocus}">
<MWEditor v-if="updateAddSRShow"
type="issueInfo"
:mdValue="replyInfo.commentMd"
:htmlValue="replyInfo.comment"
@setValue="setMdValue"
@getEditorType="getEditorType">
</MWEditor>
<div class="vr mt10">
<div class="emcs-btn bold new" :class="{'opacity' : btnLoading}" :loading="btnLoading" @click="submit">提交</div>
</div>
</div>
判断当前是否聚焦的js
let _dom = this.isMarkdown === 'true' ? ".auto-textarea-input" : '.w-e-text'
let _MWEditor = document.querySelector(_dom)
let _activeElement = document.activeElement
let that = this
_MWEditor.addEventListener("focus", function () {
let _hasFocus = document.hasFocus()
let _activeElement = document.activeElement
if(_MWEditor === _activeElement) that.hasFocus = true
else that.hasFocus = false
})
_MWEditor.addEventListener("blur", function () {
let _hasFocus = document.hasFocus()
let _activeElement = document.activeElement
if(_MWEditor === _activeElement) that.hasFocus = true
else that.hasFocus = false
})