FrankKai / FrankKai.github.io

FE blog
https://frankkai.github.io/
363 stars 39 forks source link

DOM那些事儿 #78

Open FrankKai opened 6 years ago

FrankKai commented 6 years ago
FrankKai commented 4 years ago

如何用js生成标签

var element = document.createElement(tagName[, options]);

  1. tagName列表在哪里? 无需列表,一般来说就是尖括号里的东西。 例如:
    <audio></audio>
    <p></p>

    如果实在不放心,打印出标签可以看到:

    console.dir(document.createElement('p')) // console.dir(document.createElement('p'))打印出相同的结果
    // localName: 'p', nodeName: 'P'
  2. 区分大小写吗? 不区分。
FrankKai commented 4 years ago

如何模拟focus一个DOM

element.focus(options); // Object parameter

https://developer.mozilla.org/en-US/docs/Web/API/HTMLOrForeignElement/focus

聚焦后光标如何定位到尾部

this.$refs.richTextEditor.focus();
const el = this.$refs.richTextEditor;
const range = document.createRange();
const sel = window.getSelection();
console.log(document.activeElement);
const tailIndex = el.childNodes.length;
const tailNode = el.childNodes[tailIndex - 1];
range.setStart(tailNode, tailNode.length);
range.collapse(true);
sel.removeAllRanges();
sel.addRange(range);

https://stackoverflow.com/questions/6249095/how-to-set-caretcursor-position-in-contenteditable-element-div 最高票答案的优化版。

如何获取元素的focus状态

// target element
const targetElement = document.getElementById('targetElement');
// check for focus
const isFocused = (document.activeElement === targetElement);
// vue
computed: {
    isEditorFocused() {
      const targetElement = this.$refs.richTextEditor;
      return targetElement === document.activeElement;
    },
}

https://stackoverflow.com/questions/36430561/how-can-i-check-if-my-element-id-has-focus cv前端开发。

FrankKai commented 4 years ago

如何检测一个event listener在一个DOM上是否已经注册?

Multiple identical event listeners If multiple identical EventListeners are registered on the same EventTarget with the same parameters, the duplicate instances are discarded. They do not cause the EventListener to be called twice, and they do not need to be removed manually with the removeEventListener() method.

Note, however that when using an anonymous function as the handler, such listeners will NOT be identical, because anonymous functions are not identical even if defined using the SAME unchanging source-code simply called repeatedly, even if in a loop.

即使重复注册事件监听器,也不会重复触发两次,重复的实例会被移除。 无法检测listener是否存在。

FrankKai commented 4 years ago

DOM进阶之Node Interface

DOM进阶之Node