Dom操作
关于dom, 我一无所知
参考
- https://developer.mozilla.org/zh-CN/docs/Learn/JavaScript/Client-side_web_APIs/Manipulating_documents
操作节点
var text = document.createTextNode(' — the premier source for web development knowledge.'); //建一个纯文字节点(不含标签)
linkPara.appendChild(text);//插入子元素
link.textContent = 'Mozilla Developer Network'; //设置某个标签的文本.
linkPara.parentNode.removeChild(linkPara); //删除自己.
操作样式
para.style.backgroundColor = 'black'; //对应background-color
para.setAttribute('class', 'highlight'); //设置class
WIDTH = window.innerWidth; //拿窗口宽度
div.style.width = WIDTH + 'px'; //设置div的宽度, 嘿嘿这里要拼入px. 神奇的要命.
关系
document window node element range
- document代表一个加载好的网页.
Document.createRange()
Creates aRange
object.Document.createTextNode()
Creates a text node.
- window代表一个窗口(一个tab).
- Window.document就是document
- window.parent 父窗口 通常就是window.opener
- window.location 当前窗口的url
- window.localstrorage 本地存储
- node 是一个节点, 她是一个相当基础的接口. 继承关系: eventtarget <- node <- element
- range 是一个文档片段
特别有用
start = doc.caretRangeFromPoint(startX, startY);
end = doc.caretRangeFromPoint(endX, endY);
range = doc.createRange();
range.setStart(start.startContainer, start.startOffset);
range.setEnd(end.startContainer, end.startOffset);
var sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);
range.insertNode(img);
大神的模拟代码
if (!document.caretRangeFromPoint) {
document.caretRangeFromPoint = function(x, y) {
var log = "";
function inRect(x, y, rect) {
return x >= rect.left && x <= rect.right && y >= rect.top && y <= rect.bottom;
}
function inObject(x, y, object) {
var rects = object.getClientRects();
for (var i = rects.length; i--;)
if (inRect(x, y, rects[i]))
return true;
return false;
}
function getTextNodes(node, x, y) {
if (!inObject(x, y, node))
return [];
var result = [];
node = node.firstChild;
while (node) {
if (node.nodeType == 3)
result.push(node);
if (node.nodeType == 1)
result = result.concat(getTextNodes(node, x, y));
node = node.nextSibling;
}
return result;
}
var element = document.elementFromPoint(x, y);
var nodes = getTextNodes(element, x, y);
if (!nodes.length)
return null;
var node = nodes[0];
var range = document.createRange();
range.setStart(node, 0);
range.setEnd(node, 1);
for (var i = nodes.length; i--;) {
var node = nodes[i],
text = node.nodeValue;
range = document.createRange();
range.setStart(node, 0);
range.setEnd(node, text.length);
if (!inObject(x, y, range))
continue;
for (var j = text.length; j--;) {
if (text.charCodeAt(j) <= 32)
continue;
range = document.createRange();
range.setStart(node, j);
range.setEnd(node, j + 1);
if (inObject(x, y, range)) {
range.setEnd(node, j);
return range;
}
}
}
return range;
};
}
原文出处: https://stackoverflow.com/questions/3189812/creating-a-collapsed-range-from-a-pixel-position-in-ff-webkit