HTML DOM CompareDocumentPosition() 方法用于將給定節(jié)點(diǎn)位置與任何文檔中的任何其他節(jié)點(diǎn)進(jìn)行比較。該方法的返回類型是整數(shù)類型,用于描述它們?cè)谖臋n中的位置。整數(shù)返回值如指定 –
1: No relationship, the two nodes do not belong to the same document. 2: The first node (para1) is positioned after the second node (para2). 4: The first node (para1) is positioned before the second node (para2). 8: The first node (para1) is positioned inside the second node (para2). 16: The second node (para2) is positioned inside the first node (para1). 32: No relationship, or the two nodes are two attributes on the same element.
登錄后復(fù)制
語法
以下是 HTML DOM CompareDocumentPosition() 方法的語法 –
node.compareDocumentPosition(node)
登錄后復(fù)制
這里的節(jié)點(diǎn)是節(jié)點(diǎn)對(duì)象類型,指定我們要與當(dāng)前節(jié)點(diǎn)進(jìn)行比較的節(jié)點(diǎn)。
示例
讓我們看一個(gè)compareDocumentPosition的示例() 方法 –
<!DOCTYPE html> <html> <body> <p id="para1">This is a paragraph</p> <p id="para2">This is another paragraph</p> <p>Click the button to compare the position of the two paragraphs.</p> <button onclick="docPosition()">POSITION</button> <p id="Sample"></p> <script> function docPosition() { var p1 = document.getElementById("para1").lastChild; var p2 = document.getElementById("para2").lastChild; var x = p2.compareDocumentPosition(p1); document.getElementById("Sample").innerHTML = x; } </script> </body> </html>
登錄后復(fù)制
輸出
這將產(chǎn)生以下輸出 –
單擊“位置”按鈕時(shí) –
在上面的示例中 –
我們首先創(chuàng)建了兩個(gè) id 為“para1”和“的元素
第2段”。
<p id="para1">This is a paragraph</p> <p id="para2">This is another paragraph</p>
登錄后復(fù)制
然后我們創(chuàng)建了一個(gè)按鈕 POSTION,它將在用戶單擊時(shí)執(zhí)行 docPosition() 方法 –
<button onclick="docPosition()">POSITION</button>
登錄后復(fù)制
docPosition() 方法使用文檔對(duì)象上的 getElementById() 方法獲取 <p> 元素。然后,它將兩個(gè)段落的lastchild 屬性值分別賦給變量p1 和p2。
然后,我們以p1 作為參數(shù),調(diào)用p2 上的compareDocumentPosition() 方法。這意味著我們要比較 p2 相對(duì)于 p1 的位置。由于這里 p2 位于 p1 之后,因此返回值為 2 –
function docPosition() { var p1 = document.getElementById("para1").lastChild; var p2 = document.getElementById("para2").lastChild; var x = p2.compareDocumentPosition(p1); document.getElementById("Sample").innerHTML = x; }
登錄后復(fù)制
以上就是HTML DOM compareDocumentPosition() 方法
比較文檔位置的詳細(xì)內(nèi)容,更多請(qǐng)關(guān)注www.92cms.cn其它相關(guān)文章!